【问题标题】:Pandas Boolean Indexing IssuePandas 布尔索引问题
【发布时间】:2020-12-09 16:37:03
【问题描述】:

谁能解释以下行为。我希望返回所有三行。

import pandas as pd

test_dict = {
    'col1':[None, None, None],
    'col2':[True, False, True],
    'col3':[True, True, False]
}

df = pd.DataFrame(test_dict)

df[ df.col1 | df.col2 | df.col3 ]
>>> Return only first two rows (index 0 and 1)

使用df.fillna('')None 值替换为空字符串似乎可以解决这个问题,但我不明白为什么如果None 是一个问题,前两行工作正常。

更改比较的顺序也会对其产生影响。如果我在掩码中交换 col2col3,则不再返回索引为 1 的行,而是返回索引为 2 的行。如果 col1 排在最后,则返回所有行。

【问题讨论】:

    标签: python pandas dataframe boolean


    【解决方案1】:

    问题是评估是从左到右的。那是

    df.col1 | df.col2 | df.col3 == (df.col1 | df.col2) | df.col3
    

    现在,我认为这是 Pandas 中的一个实现选择,None | True 被评估为False。所以在这种情况下(df.col1 | df.col2) 是所有False。这就是为什么您只能看到第一行。

    解决这个问题。使用

    df[df.any(axis=1)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多