【问题标题】:Multselecting in Pandas using .loc使用 .loc 在 Pandas 中进行多选
【发布时间】: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


【解决方案1】:

您需要将比较括起来为(df['State'] == 'TX') & (df['City'] == 'Arlington')。在 Python 中,& 等位运算符的优先级高于== 等比较运算符。

【讨论】:

    猜你喜欢
    • 2018-12-04
    • 2018-05-24
    • 2017-12-07
    • 2021-12-02
    • 2020-04-02
    • 1970-01-01
    • 2014-08-17
    • 2018-08-18
    • 1970-01-01
    相关资源
    最近更新 更多