【问题标题】:Melt multiple boolean columns in a single column in pandas在熊猫的单列中融化多个布尔列
【发布时间】:2020-01-11 15:42:44
【问题描述】:

我有一个这样的熊猫数据框

  Windows Linux Mac
0 True    False False
1 False   True  False
2 False   False True

我想像这样将这三列组合成一列

  OS
0 Windows
1 Linux
2 Mac

我知道我可以写一个这样的简单函数

def aggregate_os(row):
   if row['Windows'] == True:
      return 'Windows'
   if row['Linux'] == True:
      return 'Linux'
   if row['Mac'] == True:
      return 'Mac'

我可以这样称呼

df['OS'] = df.apply(aggregate_os, axis=1)

问题是我的数据集很大,这个解决方案太慢了。有没有更有效的方法来进行这种聚合?

【问题讨论】:

    标签: python-3.x pandas performance dataframe


    【解决方案1】:

    idxmax

    df.idxmax(1).to_frame('OS')
    
            OS
    0  Windows
    1    Linux
    2      Mac
    

    np.select

    pd.DataFrame(
        {'OS': np.select([*map(df.get, df)], [*df])},
        df.index
    )
    
            OS
    0  Windows
    1    Linux
    2      Mac
    

    dot

    df.dot(df.columns).to_frame('OS')
    
            OS
    0  Windows
    1    Linux
    2      Mac
    

    np.where

    假设每行只有一个True

    pd.DataFrame(
       {'OS': df.columns[np.where(df)[1]]},
        df.index
    )
    
            OS
    0  Windows
    1    Linux
    2      Mac
    

    【讨论】:

      【解决方案2】:

      boolean indexingstackrename 一起使用

      df_new = df.stack()
      df_new[df_new].reset_index(level=1).rename(columns={'level_1':'OS'}).drop(columns=0)
      

      输出

              OS
      0  Windows
      1    Linux
      2      Mac
      

      【讨论】:

        猜你喜欢
        • 2018-09-23
        • 2020-03-11
        • 1970-01-01
        • 2021-03-02
        • 1970-01-01
        • 2018-02-22
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        相关资源
        最近更新 更多