我在 pandas 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
关于python - 根据与其他 2 列相关的条件创建一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38096144/