【发布时间】:2017-03-05 16:32:48
【问题描述】:
我已成功使用.loc 分配过滤数据集的列,但现在我需要使用两个过滤器过滤数据集并得到以下错误。我正在尝试使用 & 运算符,就像您只是过滤一样。
TypeError: cannot compare a dtyped [object] array with a scalar of type [bool]
代码:
import pandas as pd
df = pd.DataFrame(data=[['Arlington', 'MA'],
['Arlington', 'TX'],
['Dallas', 'TX']],
columns=['City', 'State'])
df.loc[(df['State'] == 'TX' & df['City'] == 'Arlington'), 'New Column'] = 10
print df
期望的输出:
City State New Column
0 Arlington MA NAN
1 Arlington TX 10
2 Dallas TX NaN
【问题讨论】:
-
您需要将比较用括号括起来为
(df['State'] == 'TX') & (df['City'] == 'Arlington')。 -
@BrenBarn,你说得对,谢谢。为什么不作为答案发布,以便我接受最佳答案?
-
请注意,您没有使用
&运算符“就像您只是过滤一样”。如果您尝试使用您的条件进行过滤而不是分配,您将得到同样的错误。
标签: python python-2.7 pandas