Syntax
df[new_column_name] = 'value'
Example
df['Country'] = 'India'
Above statement add new column ‘Country’ to the DataFrame with a static value ‘India’.
add_static_new_column.py
import pandas as pd
# Create a sample DataFrame
data = {'Name': ['Krishna', 'Ram', 'Joel', 'Gopi', 'Jitendra', "Raj"],
'Age': [34, 25, 29, 41, 52, 23],
'City': ['Bangalore', 'Chennai', 'Hyderabad', 'Hyderabad', 'Bangalore', 'Chennai']}
df = pd.DataFrame(data)
print(df)
# Add new column Country with value 'India'
print('\nAdd new column Country with value "India"')
df['Country'] = 'India'
print(df)
Output
Name Age City 0 Krishna 34 Bangalore 1 Ram 25 Chennai 2 Joel 29 Hyderabad 3 Gopi 41 Hyderabad 4 Jitendra 52 Bangalore 5 Raj 23 Chennai Add new column Country with value "India" Name Age City Country 0 Krishna 34 Bangalore India 1 Ram 25 Chennai India 2 Joel 29 Hyderabad India 3 Gopi 41 Hyderabad India 4 Jitendra 52 Bangalore India 5 Raj 23 Chennai India
As you see the output,
a. new column ‘Country’ is add with a static value ‘India’ across all the rows.
b. New column is added after all the columns (in our case at index 3)
No comments:
Post a Comment