【问题标题】:Replace all Trues in a boolean dataframe with cell position用单元格位置替换布尔数据框中的所有 True
【发布时间】:2020-11-27 02:47:29
【问题描述】:

我有一个布尔数据框,想用单元格的位置(作为元组)替换 True 单元格。示例:

import pandas as pd

df = pd.DataFrame({'A': [True, False, False],
                  'B': [False, True, True]})

我尝试了 heredf.mask(df, df.index) 的修改版本(例如,尝试 iloc),但没有成功。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    让我们尝试stack 将数据框重塑为系列,然后使用布尔索引和loc 来填充使用np.argwhere 获得的索引,最后使用unstack 重塑回数据框:

    m = df.stack()
    m.loc[m] = pd.Series(map(tuple, np.argwhere(df.to_numpy())), index=m[m].index)
    out = m.unstack()
    

    或者,您也可以尝试np.argwhere 获取索引并使用iat 的索引来设置True 单元格中的值及其相应的索引:

    out = df.astype(object)
    for r, c in np.argwhere(df.to_numpy()):
        out.iat[r, c] = (r, c)
    

    结果:

    print(out)
    
            A       B
    0  (0, 0)   False
    1   False  (1, 1)
    2   False  (2, 1)
    

    【讨论】:

      【解决方案2】:

      这样的?

      import pandas
      
      df = pandas.DataFrame([
          {"A": True, "B": False},
          {"A": False, "B": True},
          {"A": False, "B": True},
      ])
      
      for column in df.columns:
          for index in df.loc[df[column] == True].index:
              df.iloc[index, df.columns.get_loc(column)] = str((index, df.columns.get_loc(column),))
      print(df)
      

      输出:

              A       B
      0  (0, 0)   False
      1   False  (1, 1)
      2   False  (2, 1)
      

      【讨论】:

      • 我的错,修复了答案
      • 这似乎有效。谢谢。我正在进一步测试它。用list(df) 替换["A", "B"] 怎么样?为了更通用。
      • 你可以做 df.columns(不要做 list(DF))
      猜你喜欢
      • 2020-08-29
      • 2020-06-27
      • 1970-01-01
      • 2020-09-25
      • 2014-01-19
      • 2023-03-24
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      相关资源
      最近更新 更多