【问题标题】:How to check if a Pandas Dataframe column contains a value? [duplicate]如何检查 Pandas Dataframe 列是否包含值? [复制]
【发布时间】:2021-12-24 15:32:23
【问题描述】:

我想检查 pandas.DataFrame 列是否包含特定值。例如,这个玩具数据框在"two" 列中有一个"h"

import pandas as pd
df = pd.DataFrame(
    np.array(list("abcdefghi")).reshape((3, 3)),
    columns=["one", "two", "three"]
)
df
  one two three
0   a   b     c
1   d   e     f
2   g   h     i

但令人惊讶的是,

"h" in df["two"]

计算为False

我的问题是:找出 DataFrame 列(或一般pandas.Series)是否包含特定值的最清晰方法是什么?

【问题讨论】:

    标签: pandas


    【解决方案1】:

    df["two"] 是一个pandas.Series,如下所示:

    0    b
    1    e
    2    h
    

    事实证明,in 运算符检查的是索引,而不是值。即

    2 in df["two"]
    

    评估为True

    因此必须明确检查以下值:

    "h" in df["two"].values
    

    计算结果为True

    【讨论】:

      猜你喜欢
      • 2018-05-10
      • 2021-09-22
      • 2020-09-07
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 2018-05-25
      • 2017-05-03
      相关资源
      最近更新 更多