Adding new column to existing DataFrame in Pandas



Pandas Data Frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns. It can be created using python dict, list and series etc. In this article we will see how to add a new column to an existing data frame. So first let's create a data frame using pandas series. In the below example we are converting a pandas series to a Data Frame of one column, giving it a column name Month_no.

Example

 Live Demo

import pandas as pd
s = pd.Series([6,8,3,1,12])
df = pd.DataFrame(s,columns=['Month_No'])
print (df)

Output

Running the above code gives us the following result:

   Month_No
0       6
1       8
2       3
3       1
4       12

using insert() function

We can use the insert() function of pandas which will insert the column at the position specified by its index. Below we add No of Days in a month as a column to the existing pandas DataFrame at index position 1.

Example

 Live Demo

import pandas as pd
s = pd.Series([6,8,3,1,12])
df = pd.DataFrame(s,columns=['Month_No'])

# Insert the new column at position 1.
df.insert(1,"No_of_days",[30,31,31,31,31],True)
print (df)

Output

Running the above code gives us the following result −

   Month_No No_of_days
0       6       30
1       8       31
2       3       31
3       1       31
4       12      31

Using assign() function

The assign() function

Example

 Live Demo

import pandas as pd
s = pd.Series([6,8,3,1,12])
df = pd.DataFrame(s,columns=['Month_No'])

# Insert a column at the end
df = df.assign(No_of_days = [30,31,31,31,31])

print (df)

Output

Running the above code gives us the following result −

   Month_No No_of_days
0       6       30
1       8       31
2       3       31
3       1       31
4       12      31

Advertisements