【问题标题】:Get Row and Column name of a specific cell in DataFrame获取 DataFrame 中特定单元格的行和列名称
【发布时间】:2021-01-11 20:51:04
【问题描述】:

我有这个数据框,它代表我拥有的另一个数据框的相关矩阵。我想遍历相关矩阵并获取单元格值为 True 的每一行和每一列的名称。例如,我希望它打印:

REB DREB . . .

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:
    reqd_Index = df[df['id']== True].index.tolist()
    print(reqd_Index)
    

    【讨论】:

      【解决方案2】:

      假设您有以下数据框:

      df = pd.DataFrame({'AST': {'id': False, 'REB': False, 'FG3a': False},
       'BLK': {'id': False, 'REB': False, 'FG3a': False},
       'DREB': {'id': False, 'REB': True, 'FG3a': False}})
      
              AST    BLK   DREB
      id    False  False  False
      REB   False  False   True
      FG3a  False  False  False
      
      1. 您可以melt DataFrame 并返回您感兴趣的行

      true = df.melt(ignore_index=False)
      true[true['value']]
      
              variable  value
      REB     DREB      True
      
      1. 如果你想print,你可以这样做:

      true = df.melt(ignore_index=False)
      true = true[true['value']]
      [print(x,y) for (x,y) in zip(true.index, true['variable'])]
      
      REB DREB
      
      1. 如果你想要output in an array,那么你可以这样做:

      true = df.melt(ignore_index=False).reset_index()
      true[true['value']].drop('value', axis=1).values
      
      array([['FG3a', 'BLK'],
             ['REB', 'DREB']], dtype=object)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-20
        • 1970-01-01
        相关资源
        最近更新 更多