根据与其他2列有关的条件创建一列
问题内容:
我在熊猫DataFrame中有两列(我们将其称为“ col1”和“ col2”)。两者都包含True / False值。
我需要从这两列中创建第三列(’col3’),如果两列中的一列在该记录中具有True值,则该列将具有记录的True值。
目前,我正在使用以下方法:
col3 = []
for index, row in df.iterrows():
if df.ix[index, 'col1'] == True or df.ix[index, 'col2'] == True:
col3.append(True)
else:
col3.append(False)
df['col3'] = col3
对于我的数据集,它的工作速度足够快,但是有没有办法以单线/矢量化的方式进行呢?也许使用两个嵌套np.where()
语句?
问题答案:
您可以使用np.logical_or
以下方法:
In [236]:
df = pd.DataFrame({'col1':[True,False,False], 'col2':[False,True,False]})
df
Out[236]:
col1 col2
0 True False
1 False True
2 False False
In [239]:
df['col3'] = np.logical_or(df['col1'], df['col2'])
df
Out[239]:
col1 col2 col3
0 True False True
1 False True True
2 False False False
或使用|
运算符:
In [240]:
df['col3'] = df['col1'] | df['col2']
df
Out[240]:
col1 col2 col3
0 True False True
1 False True True
2 False False False