正如爱德密友指出,你可以使用isin
method:
table['cond5'] = table['OPINION'].isin(['buy', 'neutral'])
isin
检查确切的平等。也许这将是最简单和最易读的。
要解决
table["cond5"] = table.OPINION == "buy" or table.OPINION == "neutral"
使用
table["cond5"] = (table['OPINION'] == "buy") | (table['OPINION'] == "neutral")
括号是必要的,因为|
具有higher precedence (binding power)比==
。
x or y
要求x
和y
是布尔值。
(table['OPINION'] == "buy") or (table['OPINION'] == "neutral")
自从Series can no be reduced to a single boolean value产生错误。
因此改为使用逻辑运算符或运算符|
,它以系列元素的方式取值为or
。
另一个替代方案是
import numpy as np
table["cond5"] = np.logical_or.reduce([(table['OPINION'] == val) for val in ('buy', 'neutral')])
如果('buy', 'neutral')
是一个较长的元组可能是有用的。
又一选择是使用大熊猫vectorized string method, str.contains
:
table["cond5"] = table['OPINION'].str.contains(r'buy|neutral')
str.contains
执行用于在一个循环Cythonized在table['OPINION']
每个项的图案r'buy|neutral'
一个正则表达式的搜索。
现在如何决定使用哪一个?下面是使用IPython一个timeit基准:
In [10]: table = pd.DataFrame({'OPINION':np.random.choice(['buy','neutral','sell',''], size=10**6)})
In [11]: %timeit (table['OPINION'] == "buy") | (table['OPINION'] == "neutral")
10 loops, best of 3: 121 ms per loop
In [12]: %timeit np.logical_or.reduce([(table['OPINION'] == val) for val in ('buy', 'neutral')])
1 loops, best of 3: 204 ms per loop
In [13]: %timeit table['OPINION'].str.contains(r'buy|neutral')
1 loops, best of 3: 474 ms per loop
In [14]: %timeit table['OPINION'].isin(['buy', 'neutral'])
10 loops, best of 3: 40 ms per loop
所以看起来isin
最快。
另一种方法是'table ['OPINION']。isin(['buy','neutral'])' – EdChum 2015-02-24 13:01:35
@EdChum:是的,谢谢,我错过了一个.. – unutbu 2015-02-24 13:03:03