How to assign a new column in a Pandas DataFrame?

How to assign a new column in a Pandas DataFrame?

This recipe helps you assign a new column in a Pandas DataFrame
In [1]:
## How to assign a new column in a Pandas DataFrame
def Kickstarter_Example_71():
    print()
    print(format('How to assign a new column in a Pandas DataFrame','*^82'))

    import warnings
    warnings.filterwarnings("ignore")

    # load libraries
    import pandas as pd

    # Create empty dataframe
    df = pd.DataFrame()

    # Create a column
    df['StudentName'] = ['John', 'Steve', 'Sarah']

    # View dataframe
    print(); print(df)

    # Assign a new column to df called 'age' with a list of ages
    df = df.assign(Marks = [71, 82, 89])

    # View dataframe
    print(); print(df)

Kickstarter_Example_71()
*****************How to assign a new column in a Pandas DataFrame*****************

  StudentName
0        John
1       Steve
2       Sarah

  StudentName  Marks
0        John     71
1       Steve     82
2       Sarah     89


Stuck at work?
Can't find the recipe you are looking for. Let us know and we will find an expert to create the recipe for you. Click here
Companies using this Recipe
1 developer from HCL
1 developer from Megasoft
1 developer from Altimetrik
1 developer from HvH
1 developer from Scotiabank
1 developer from ANAC
1 developer from KPMG
1 developer from Vodafone
1 developer from Cisco
1 developer from LTI