【问题标题】:How to get pandas dataframe series name given a column value?如何在给定列值的情况下获取熊猫数据框系列名称?
【发布时间】:2018-07-23 02:54:34
【问题描述】:

我有一个带有一堆名称和系列的 python pandas 数据框,我创建了一个最后一列,我总结了系列。我只想获取系列之和等于 0 的行名,以便稍后删除这些行。我的数据框如下(我创建的最后一列只是为了总结系列):

      1   2   3   4  total
Ash   1   0   1   1  3
Bel   0   0   0   0  0
Cay   1   0   0   0  1
Jeg   0   1   1   1  3
Jut   1   1   1   1  4

基于最后一列,“Bel”系列为 0,因此我希望能够仅打印出该名称,然后我可以删除该行或保留这些行的记录。

这是我目前的代码:

def check_empty(df):
    df['total'] = df.sum(axis=1) # create the 'total' column to find zeroes
    for values in df['total']:
        if values == 0:
            print(df.index[values)

但这显然是错误的,因为我将 0 的索引传递给这个循环,它总是会打印第一行的名称。不确定我可以在这里实现什么方法?

下面有很好的解决方案,我还找到了一种使用更简单的python技能的方法,枚举(因为我仍然觉得列表理解很难写):

 def check_empty(df):
     df['total'] = df.sum(axis=1)
     for name, values in enumerate(df['total']):
         if values == 0:
            print(df.index[name])

【问题讨论】:

  • 你在寻找类似df.loc[df['total'] == 0].index.tolist()的东西吗?
  • 你也可以试试:df[df['total'] == 0].index.values.tolist()
  • 是的,行得通!但我也想出了一种方法,使用我的基本 Python 技能和枚举(见编辑)。
  • 您也可以使用df.iterrows() 来遍历行。

标签: python pandas indexing


【解决方案1】:

一种可能的方法是使用total 中的值过滤df

def check_empty(df):
    df['total'] = df.sum(axis=1) # create the 'total' column to find zeroes
    index = df[df['total'] == 0].index.values.tolist()
    print(index)

如果您想遍历行然后,使用df.iterrows() 也可能是其他方式:

def check_empty(df):
    df['total'] = df.sum(axis=1) # create the 'total' column to find zeroes
    for index, row in df.iterrows():
        if row['total'] == 0:
            print(index)

【讨论】:

    【解决方案2】:

    另一个选项是np.where

    import numpy as np
    df.iloc[np.where(df.loc[:, 'total'] == 0)]
    

    输出:

         1  2  3  4  total
    Bel  0  0  0  0      0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-25
      • 2018-02-17
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 2020-06-03
      • 1970-01-01
      相关资源
      最近更新 更多