python - 使用逻辑( bool )表达式对 Pandas Dataframe 进行切片

标签 python pandas slice logical-operators boolean-expression

当我尝试使用逻辑表达式对我的 Pandas 数据框进行切片时出现异常。

我的数据具有以下形式:

df
    GDP_norm    SP500_Index_deflated_norm
Year        
1980    2.121190    0.769400
1981    2.176224    0.843933
1982    2.134638    0.700833
1983    2.233525    0.829402
1984    2.395658    0.923654
1985    2.497204    0.922986
1986    2.584896    1.09770

df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 38 entries, 1980 to 2017
Data columns (total 2 columns):
GDP_norm                     38 non-null float64
SP500_Index_deflated_norm    38 non-null float64
dtypes: float64(2)
memory usage: 912.0 bytes

命令如下:

df[((df['GDP_norm'] >=3.5 & df['GDP_norm'] <= 4.5) & (df['SP500_Index_deflated_norm'] > 3)) | (

   (df['GDP_norm'] >= 4.0 & df['GDP_norm'] <= 5.0) & (df['SP500_Index_deflated_norm'] < 3.5))]

错误信息如下:

TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]

最佳答案

我建议单独创建 bool 掩码以获得更好的可读性和更容易的错误处理。

m1m2 代码中缺少(),问题出在运算符优先级上:

docs - 6.16。运算符优先级 & 具有更高的优先级,如 >=:

Operator                                Description

lambda                                  Lambda expression
if – else                               Conditional expression
or                                      Boolean OR
and                                     Boolean AND
not x                                   Boolean NOT
in, not in, is, is not,                 Comparisons, including membership tests    
<, <=, >, >=, !=, ==                    and identity tests
|                                       Bitwise OR
^                                       Bitwise XOR
&                                       Bitwise AND

(expressions...), [expressions...],     Binding or tuple display, list display,       
{key: value...}, {expressions...}       dictionary display, set display

m1 = (df['GDP_norm'] >=3.5) & (df['GDP_norm'] <= 4.5)
m2 = (df['GDP_norm'] >= 4.0) & (df['GDP_norm'] <= 5.0)

m3 = m1 & (df['SP500_Index_deflated_norm'] > 3)
m4 = m2 & (df['SP500_Index_deflated_norm'] < 3.5)

df[m3 | m4]

关于python - 使用逻辑( bool )表达式对 Pandas Dataframe 进行切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51153010/

相关文章:

python unhashable 类型 - 发布 xml 数据

python - scipy第一次启动慢

python - Django Rest Framework 按类别重新组合查询集

Python 在字符串中执行操作

python - 数据帧索引(仅)到 CSV python

python - 按以某个字符串开头的键对字典进行切片

python使用排名号来选择两个数据帧之间的值

python - 只需将数据放在另一个 pandas python 之上

python - 基于出现次数的 Pandas 新数据框

python - 字符串切片参数