这是我的数据框:
import pandas as pd
df = pd.DataFrame({'animal':['dog','cat','rabbit','pig'],'color':['red','green','blue','purple'],\
'season':['spring,','summer','fall','winter']})
我有一个列表
l = ['dog','green','purple']
这些数据框和列表,我想补充另一列到DF,这实际上是一个结果,如果列“动物”或列“色”相匹配的l(列表)的一些项目。
所以,我想要的结果(数据帧)低于(我想表达一个表):
pd.DataFrame({'animal':['dog','cat','rabbit','pig'],
'color':['red','green','blue','purple'],
'season':['spring,','summer','fall','winter'],
'tar_rm':[1,1,0,1] })
我必须在列的每个行迭代列表?我相信,大熊猫的一个优势正在广播,但我不知道这是可能在这里...
采用:
cols = ['animal','color']
df['tar_rm'] = df[cols].isin(l).any(axis=1).astype(int)
print (df)
animal color season tar_rm
0 dog red spring 1
1 cat green summer 1
2 rabbit blue fall 0
3 pig purple winter 1
细节:
首先由DataFrame
比较DataFrame.isin
的过滤列:
print (df[cols].isin(l))
animal color
0 True False
1 False True
2 False False
3 False True
然后由测试True
每行,如果至少一个DataFrame.any
:
print (df[cols].isin(l).any(axis=1))
0 True
1 True
2 False
3 True
dtype: bool
最后一投布尔为整数:
print (df[cols].isin(l).any(axis=1).astype(int))
0 1
1 1
2 0
3 1
dtype: int32
如果性能是重要的isin
每列分别比较,转换成numpy的阵列,通过按位或和去年投地整数链:
df['tar_rm'] = (df['animal'].isin(l).values | df['color'].isin(l).values).astype(int)
性能:取决于行数,匹配的行和列表值的数数,实际数据,因此最好的测试:
l = ['dog','green','purple']
df = pd.concat([df] * 100000, ignore_index=True).sample(1)
In [173]: %timeit df['tar_rm'] = df[['animal','color']].isin(l).any(axis=1).astype(int)
2.11 ms ± 250 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [174]: %timeit df['tar_rm'] = (df['animal'].isin(l).values | df['color'].isin(l).values).astype(int)
487 µs ± 9.87 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [175]: %timeit df['tar_rm'] = np.where(df['animal'].isin(l) | df['color'].isin(l), 1, 0)
805 µs ± 15.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
使用numpy
df['tar_rm'] = np.where(df['animal'].isin(l) | df['color'].isin(l), 1, 0)
产量
animal color season tar_rm
0 dog red spring, 1
1 cat green summer 1
2 rabbit blue fall 0
3 pig purple winter 1