Adding a Column to DataFrame

Write a Pandas program to add an additional column ‘color’ to a given dataframe.

Example 1:

Input: DataFrame 
Output: DataFrame with an additional 'color' column

Example 2:

Input: DataFrame 
Output: DataFrame with an additional 'color' column

You can simply add a new column to DataFrame by assigning it to df[‘new_column_name’].

import pandas as pd

def add_column(df, column_values):
    df['color'] = column_values
    return df

df1 = pd.DataFrame({'name': ['Tom', 'Jack', 'Steve', 'Ricky'], 'score': [85, 90, 87, 91]})
df2 = pd.DataFrame({'name': ['Adam', 'Eve', 'Stark', 'Rogers'], 'score': [88, 92, 95, 97]})

print(add_column(df1, ['Red', 'Green', 'Blue', 'Black']))
print(add_column(df2, ['Purple', 'Yellow', 'Pink', 'Brown']))

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!