小编sm1*_*994的帖子

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

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

  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)

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

performance dataframe python-3.x pandas

6
推荐指数
1
解决办法
1045
查看次数

标签 统计

dataframe ×1

pandas ×1

performance ×1

python-3.x ×1