【问题标题】:Pandas: Find row containing several values arbitrarily distributed over columnsPandas:查找包含任意分布在列上的多个值的行
【发布时间】:2021-09-01 23:26:19
【问题描述】:

我正在为以下问题寻找一个很好的解决方案:我有一个 pandas DataFrame,我只知道其中一行包含多个任意分布在列上的值。我想找到那一行。

示例: 以下两个数据框都只有一行包含值“嘿”、“这里”和“我在”:

df = pd.DataFrame({"a": (np.nan, 1, "hey", 5, 100), "b": ("testing", np.nan, "here", "what", -3),
                   "c": (1, "two", 3, "four", 5), "d": ("ay", "why", "I am", np.nan, 4)})

df:
     a        b     c     d
0  NaN  testing     1    ay
1    1      NaN   two   why
2  hey     here     3  I am
3    5     what  four   NaN
4  100       -3     5     4

在 df 第 2 行(第三行)中包含值“嘿”、“这里”和“我在”。

df2 = pd.DataFrame({"a": (np.nan, 1, np.nan, 5, "I am"), "b": ("testing", np.nan, "something", "what", -3),
                    "c": (1, "two", 3, "four", "hey"), "d": ("ay", "why", "I am", np.nan, "here")})
df2:
      a          b     c     d
0   NaN    testing     1    ay
1     1        NaN   two   why
2   NaN  something     3  I am
3     5       what  four   NaN
4  I am         -3   hey  here

在 df2 第 4 行(第五行)中包含值“嘿”、“这里”和“我在”。

如何获取包含值的相应行的行索引? 我的解决方案有效,但很丑:

row_id = [id for id, row in df.iterrows() if hasattr(row, "str") and
          (row.str.contains("hey").sum() +
           row.str.contains("here").sum() +
           row.str.contains("I am").sum() == 3)][0]

我想这个问题必须有一个更好、更 Pythonic 的解决方案。

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    这是一种解决问题的pythonic方法。屏蔽不在列表l 中的值,然后使用nunique 沿列轴计算唯一值并将计数与3 进行比较以创建布尔掩码

    l = ['hey', 'here', 'I am']
    s = df.where(df.isin(l)).nunique(axis=1).eq(3)
    

    print(s)
    0    False
    1    False
    2     True
    3    False
    4    False
    dtype: bool
    
    print(s[s].index)
    Int64Index([2], dtype='int64')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-22
      • 2018-05-12
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      相关资源
      最近更新 更多