[英]Adding column to pandas dataframe taking values from list in other column
[英]Adding Column to pandas DataFrame in Vectorized way conditioning on other column values
我有一个熊猫数据框df
>>> df
a b c
0 1 1 0
1 1 -1 1
2 1 0 0
现在我想在列a
和b
上添加一个新列 df['e'] 条件。 我想以矢量化的方式创建新列。
现在,我正在做以下事情:
df["e"] = [-1 if (df['a'] == 1 and df['b'] == 1) else 1]
应该输出:
>>> df
a b c e
0 1 1 0 -1
1 1 -1 1 1
2 1 0 0 1
但我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/hmishfaq/anaconda/lib/python2.7/site-packages/pandas/core/generic.py", line 917, in __nonzero__
.format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我做错了什么,这里矢量化的正确方法是什么?
PS:我需要使用的原始数据框非常大,因此 for-loop 需要很长时间才能做到这一点。
您可以使用非常快的numpy.where
:
df['e'] = np.where((df['a'] == 1) & (df['b'] == 1), -1, 1)
print (df)
a b c e
0 1 1 0 -1
1 1 -1 1 1
2 1 0 0 1
您的错误源于您使用的是and
,而不是&
。 切换到后者,你的错误就会消失。
解决方案:
df["e"] = [-1 if (df['a'] == 1 & df['b'] == 1) else 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.