【问题标题】:Selecting rows from pandas DataFrame using two columns使用两列从 pandas DataFrame 中选择行
【发布时间】:2015-01-22 11:35:50
【问题描述】:

我在 pandas 中有一个 DataFrame,我想根据两列的值从中选择一个行子集。

test_df = DataFrame({'Topic' : ['A','A','A','B','B'], 'Characteristic' : ['Population','Other','Other','Other','Other'], 'Total' : [25, 22, 21, 20, 30]})

当我使用此代码时,它按预期工作并返回第一行:

bool1 = test_df['Topic']=='A' 
bool2 = test_df['Characteristic']=='Population'

test_df[bool1 & bool2]

但是当我尝试如下在一行中完成所有操作时,

test_df[test_df['Topic']=='A' & test_df['Characteristic']=='Population']

我得到“TypeError: cannot compare a dtyped [object] array with a scalar of type [bool]”

为什么?有没有一个好方法可以一步完成?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    只需要加括号:

    >>> test_df[(test_df['Topic']=='A') & (test_df['Characteristic']=='Population')]
      Characteristic Topic  Total
    0     Population     A     25
    

    或者,您可以使用query 方法,以避免test_df 的重复:

    >>> test_df.query("Topic == 'A' and Characteristic == 'Population'")
      Characteristic Topic  Total
    0     Population     A     25
    

    【讨论】:

    • 很高兴您包含了查询示例。虽然它是“唯一的”语法糖,但它使代码更加更具可读性。
    猜你喜欢
    • 2016-05-01
    • 2018-06-08
    • 1970-01-01
    • 2015-05-30
    • 2019-12-02
    • 1970-01-01
    • 2021-05-07
    • 2017-01-14
    • 2016-06-19
    相关资源
    最近更新 更多