Select Page

How to Add a New Column to an Existing Pandas DataFrame in Python

by | Programming, Python, Tips

This tutorial will explain several ways to add new columns to an existing DataFrame in Pandas with code examples.


Using DataFrame.insert()

We can use the DataFrame.insert() method to insert a column at any position in the DataFrame.

import pandas as pd

data = {'Name': ['electron', 'muon', 'proton', 'neutron'],
'Mass': [0.511, 105.7, 938.3, 939.6],
'Charge': [-1, -1, 1, 0]}

df = pd.DataFrame(data)

print(df)
      Name     Mass  Charge
0  electron    0.511      -1
1      muon  105.700      -1
2    proton  938.300       1
3   neutron  939.600       0
df.insert(3, 'Spin', [1/2, 1/2, 1/2, 1/2], True)

print(df)
     Name     Mass  Charge  Spin
0  electron    0.511      -1   0.5
1      muon  105.700      -1   0.5
2    proton  938.300       1   0.5
3   neutron  939.600       0   0.5

Using DataFrame.assign()

We can use the DataFrame.assign() method to assign one or more columns to an existing DataFrame. The assign method will create a new DataFrame with the new columns added to the existing DataFrame.

import pandas as pd

data = {'Name': ['electron', 'muon', 'proton', 'neutron'],
'Mass': [0.511, 105.7, 938.3, 939.6],
'Charge': [-1, -1, 1, 0]}

df = pd.DataFrame(data)

print(df)
      Name     Mass  Charge
0  electron    0.511      -1
1      muon  105.700      -1
2    proton  938.300       1
3   neutron  939.600       0
df2 = df.assign(Spin=[1/2, 1/2, 1/2, 1/2])

print(df2)
     Name     Mass  Charge  Spin
0  electron    0.511      -1   0.5
1      muon  105.700      -1   0.5
2    proton  938.300       1   0.5
3   neutron  939.600       0   0.5

Declaring New List as a Column

We can add a new list as a column to an existing DataFrame as follows:

import pandas as pd

data = {'Name': ['electron', 'muon', 'proton', 'neutron'],
'Mass': [0.511, 105.7, 938.3, 939.6],
'Charge': [-1, -1, 1, 0]}

df = pd.DataFrame(data)

print(df)

spin = [1/2, 1/2, 1/2, 1/2]

df['Spin'] = spin

print(df)
       Name     Mass  Charge
0  electron    0.511      -1
1      muon  105.700      -1
2    proton  938.300       1
3   neutron  939.600       0

       Name     Mass  Charge  Spin
0  electron    0.511      -1   0.5
1      muon  105.700      -1   0.5
2    proton  938.300       1   0.5
3   neutron  939.600       0   0.5

Summary

Congratulations on reading to the end of this tutorial. The AttributeError: ‘DataFrame’ object has no attribute ‘concat’ occurs when you try to call the concat method on a DataFrame instead of using the built-in Pandas method.

For further reading on errors related Pandas, go to the articles:

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!