Python | Pandas dataframe.assign ()

Python Methods and Functions

Dataframe.assign() assigns new columns to the DataFrame, returning a new object (copy) with new columns added to the original ones. Existing columns to be reassigned will be overwritten.

The newly assigned column must be as long as the number of rows in the data frame.

Syntax: DataFrame. assign (** kwargs)

Parameters:
kwargs: keywords are the column names. If the values ​​are callable, they are computed on the DataFrame and assigned to the new columns. The callable must not change input DataFrame (though pandas don't check it). If the values ​​are not callable, (eg a Series, scalar, or array), they are simply assigned.

Returns: A new DataFrame with the new columns in addition to all the existing columns.

To link to the CSV file used in the code, click here

Example # 1: Assign a new column named Revised_Salary in increments of 10% of the original salary .

# import pandas as pd

import pandas as pd

 
# Create a data frame from CSV file

df = pd.read_csv ( " nba.csv " )

  
# Print the first 10 lines
# data frame for rendering

df [: 10 ]

# increase salary by 10%

df.assign (Revised_Salary = lambda x: df [ 'Salary' ]

+ df [ ' Salary' ] / 10 )

Output:

Example # 2: Assigning more than one column at a time

# pandas import as pd

import pandas as pd

 
# Create data frame from CSV file

df = pd.read_csv ( "nba.csv" )

 
# First column = & # 39; New_Team & # 39 ;, this column
# will add & # 39; _GO & # 39; at the end of each team name.
# Second column = & # 39; Revised_Salary & # 39; will increase
# salary of all employees by 10%

df.assign (New_team = lambda x: df [ ' Team' ] + '_GO'

Revised_Salary = lambda x: df [ 'Salary'

+ df [ 'Salary' ] / 10 )

Output:





Get Solution for free from DataCamp guru