我想根据其他列之一中的值向 pandas DataFrame 添加一列。
import pandas as pd
import numpy as np
Records = 100
df = pd.DataFrame (
{'ID' : range(1, Records + 1),
'Group' : np.random.choice(range(1, 41), Records, replace = True)
}
)
def Age(x):
a = list()
for i in x:
if (i >= 14 and i <= 20) or (i >= 34 and i <= 40):
a.append('65+')
else:
a.append('65-')
return a
df['Age'] = Age(df.Group)
print(df.head(10))
Group ID Age
0 11 1 65-
1 1 2 65-
2 6 3 65-
3 32 4 65-
4 31 5 65-
5 39 6 65+
6 26 7 65-
7 38 8 65+
8 26 9 65-
9 31 10 65-
这可以完成工作,但我更喜欢尽可能使用 lambda 函数,但无法使其正常工作。或者,如果可能,在创建数据框时创建 Age 列。有什么建议吗?
请您参考如下方法:
使用numpy.where什么是非常快的向量化函数:
m = ((df['Group'] >= 14) & (df['Group'] <= 20)) | ((df['Group'] >= 34) & (df['Group'] <= 40))
df['new'] = np.where(m, '65+','65-')
print (df)
Group ID Age new
0 11 1 65- 65-
1 1 2 65- 65-
2 6 3 65- 65-
3 32 4 65- 65-
4 31 5 65- 65-
5 39 6 65+ 65+
6 26 7 65- 65-
7 38 8 65+ 65+
8 26 9 65- 65-
9 31 10 65- 65-
时间:
Records = 1000000
In [94]: %timeit df['Age1'] = np.where((df['Group'] >= 14) & (df['Group'] <= 20) | (df['Group'] >= 34) & (df['Group'] <= 40), '65+','65-')
10 loops, best of 3: 123 ms per loop
In [95]: %timeit df['Age2'] = df['Group'].apply(lambda x: '65+' if ((x >= 14 and x <= 20) or (x >= 34 and x <= 40)) else '65-')
1 loop, best of 3: 253 ms per loop
