深度阅读

How to add a new column to a Pandas DataFrame?

作者
作者
2023年08月22日
更新时间
7.98 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。