在熊猫的单个列中融化多个布尔列

sm1*_*994 6 performance dataframe python-3.x pandas

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

  Windows Linux Mac
0 True    False False
1 False   True  False
2 False   False True
Run Code Online (Sandbox Code Playgroud)

我想像这样将这三列组合在一个列中

  OS
0 Windows
1 Linux
2 Mac
Run Code Online (Sandbox Code Playgroud)

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

def aggregate_os(row):
   if row['Windows'] == True:
      return 'Windows'
   if row['Linux'] == True:
      return 'Linux'
   if row['Mac'] == True:
      return 'Mac'
Run Code Online (Sandbox Code Playgroud)

我可以这样称呼

df['OS'] = df.apply(aggregate_os, axis=1)
Run Code Online (Sandbox Code Playgroud)

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

piR*_*red 6

idxmax

df.idxmax(1).to_frame('OS')

        OS
0  Windows
1    Linux
2      Mac
Run Code Online (Sandbox Code Playgroud)

np.select

pd.DataFrame(
    {'OS': np.select([*map(df.get, df)], [*df])},
    df.index
)

        OS
0  Windows
1    Linux
2      Mac
Run Code Online (Sandbox Code Playgroud)

dot

df.dot(df.columns).to_frame('OS')

        OS
0  Windows
1    Linux
2      Mac
Run Code Online (Sandbox Code Playgroud)

np.where

假设True每行只有一个

pd.DataFrame(
   {'OS': df.columns[np.where(df)[1]]},
    df.index
)

        OS
0  Windows
1    Linux
2      Mac
Run Code Online (Sandbox Code Playgroud)