我有一只熊猫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:我需要使用的原始数据文件非常大,因此-循环要花费很长时间才能完成。
发布于 2016-12-09 14:09:30
您可以使用非常快的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发布于 2019-12-26 20:15:05
您的错误源于这样一个事实:您使用的是and而不是&。切换到后者,您的错误就会消失。
解决方案:
df["e"] = [-1 if (df['a'] == 1 & df['b'] == 1) else 1]https://stackoverflow.com/questions/41062277
复制相似问题