add column name to dataframe code example
Example 1: how to give name to column in pandas
>gapminder.rename(columns={'pop':'population',
'lifeExp':'life_exp',
'gdpPercap':'gdp_per_cap'},
inplace=True)
>print(gapminder.columns)
Index([u'country', u'year', u'population', u'continent', u'life_exp',
u'gdp_per_cap'],
dtype='object')
>gapminder.head(3)
country year population continent life_exp gdp_per_cap
0 Afghanistan 1952 8425333 Asia 28.801 779.445314
1 Afghanistan 1957 9240934 Asia 30.332 820.853030
2 Afghanistan 1962 10267083 Asia 31.997 853.100710
Example 2: how to add new column to dataframe
# Import pandas package
import pandas as pd
# Define a dictionary containing Students data
data = {'Name': ['Jai', 'Princi', 'Gaurav', 'Anuj'],
'Height': [5.1, 6.2, 5.1, 5.2],
'Qualification': ['Msc', 'MA', 'Msc', 'Msc']}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
# Declare a list that is to be converted into a column
address = ['Delhi', 'Bangalore', 'Chennai', 'Patna']
# Using 'Address' as the column name
# and equating it to the list
df['Address'] = address
# Observe the result
df