在已有的DataFrame上增加新列

这是系列文章,我会按照stackoverflow上pandas相关问题投票数排序进行整理学习。不学习是会变咸鱼的~

原问题:adding new column to existing DataFrame in Python pandas,添加新的列到原有数据中,我们可以分几种情况来看。

假设原始数据如下:

1
2
3
4
5
6
import pandas as pd
import numpy as np

df = pd.DataFrame({'num_legs': [4, 2], 'num_wings': [0, 2]},
index=['dog', 'hawk'])
slen = len(df['num_legs'])

1)直接赋值

1
2
3
4
5
6
7
8
9
df['a'] = pd.Series(np.random.randn(slen), index=df.index) # index要记得添加
df['b'] = None # 添加一列值为None
df['c'] = [2, 4] # 添加列表数据

# c1和c3列的顺序是一样的, c2则与之相反,具体看下文
df['c1'] = ['no', 'yes']
df.index = [1, 0]
df['c2'] = pd.Series(['no', 'yes'])
df['c3'] = pd.Series(['no', 'yes'], index=df.index)

2)loc方法

1
2
df.loc[:,'d'] = pd.Series(np.random.randn(slen), index=df.index)
df.loc[:, 'd'] = [2, 4]

3)insert方法

insert方法使用的列名不能有重复值,连更新都不能

1
2
df.insert(len(df.columns), 'e', pd.Series(np.random.randn(slen)), index=df.index)
df.insert(len(df.columns), 'ee', [1,2])

4)assign方法

assign方法参数可以是Series、标量、列表,还可以同时添加多列

1
2
df = df.assign(f=df.num_wings.mean())  # 将num_wings这列的平均值作为新增列f的结果
df = df.assign(A=df.num_wings.sum(), B=[1,2]) # 新增列A和B

5)concat方法

1
pd.concat([df, pd.Series(['yes', 'yes']).rename('t')], axis=1) # 增加列t

注意点:

  • 每个方法的参数都可以是Series、标量、列表
  • insert方法中新增的列名不能跟已有的一样,即使更新刚刚新增的列也会出错
  • df['a']=pd.Series(['no', 'yes']的index顺序如果被修改,默认是以Series的index为准,可以通过index=df.index来指定按照原始DataFrame的index顺序