How to Add New column in DataFrame
We can easily add a new column in the existing DataFrame. The following examples will clear you, on how to add new column in DataFrame.
#1. Method :- By adding a new list or Series
import pandas as pd
data = { ‘first’ : pd.Series ( [ 1, 2, 3 ] , index= [‘a’, ‘b’, ‘c’ ] ),
‘second’ : pd.Series ( [ 10, 20, 30 ], index= [‘a’, ‘b’, ‘c’ ] ) }
df= pd.DataFrame(data)
print (df)
print (“After adding a new column in Data Frame “)
df [ ‘third’ ]= pd.Series( [ 11, 22, 33 ], index= [‘a’, ‘b’, ‘c’ ] )
print (df)
#2. Method :- By using DataFrame.insert() function
import pandas as pd
data = { ‘first’ : pd.Series ( [ 1, 2, 3 ] , index= [‘a’, ‘b’, ‘c’ ] ),
‘second’ : pd.Series ( [ 10, 20, 30 ], index= [‘a’, ‘b’, ‘c’ ] ) }
df= pd.DataFrame(data)
print (df)
print (“By using insert() addition of a new column in Data Frame “)
df.insert(1, “third ” , [ 11, 22, 33 ], True )
print (df)
#3. Method :- By using DataFrame.assign() function
import pandas as pd
data = { ‘first’ : pd.Series ( [ 1, 2, 3 ] , index= [‘a’, ‘b’, ‘c’ ] ),
‘second’ : pd.Series ( [ 10, 20, 30 ], index= [‘a’, ‘b’, ‘c’ ] ) }
df= pd.DataFrame(data)
print (df)
print (“To add a new column by using assign() it will create a new Data Frame “)
df2= df.assign(third = [ 11, 22, 33 ] )
print (df2)