How to add a new column to a Pandas DataFrame?

Published on Aug. 22, 2023, 12:18 p.m.

To add a new column to a Pandas DataFrame, you can simply assign a new column with the desired data to the DataFrame. For example:

import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) # create a DataFrame with columns A and B
df['C'] = [7, 8, 9] # add a new column C with data [7, 8, 9] to the DataFrame
print(df)

Output:

A  B  C
0  1  4  7
1  2  5  8
2  3  6  9

Alternatively, you can use the DataFrame.insert() method to add a new column to a specific position or index in the DataFrame. For example:

df.insert(1, 'C', [7, 8, 9]) # add a new column C with data [7, 8, 9] to the DataFrame at position 1
print(df)

Output:

A  C  B
0  1  7  4
1  2  8  5
2  3  9  6

Both methods allow you to add a new column to a Pandas DataFrame.

Tags: