首页 > 解决方案 > 熔化多个布尔列

问题描述

这个问题是这里已经问过的问题的扩展:Melt multiple boolean columns in a single column in pandas

如果数据看起来像:

| System | Windows | Linux | Mac|
| -------- | -------------- |
| Desktop    | True | True | False |
| Laptop | True   | True | False
| Mobile | True   | True | False
| Tablet | False | True | False

其中 ' System' 是dtype=string,其他列是dtype=boolean。我怎样才能使决赛桌看起来像这样:

| OS | System |
| --- ----- | -------------- |
| Windows| Desktop Laptop Mobile  |
| Linux | Desktop Laptop Mobile Tablet |
| Mac | |

其中System列中的值由空格分隔。

标签: python-3.xpandasdataframe

解决方案


一个想法是首先将System列转换为index并转置,然后使用DataFrame.dot带有空格分隔符的列名称进行矩阵乘法:

df1 = df.set_index('System').T
df1 = df1.dot(df1.columns + ' ').str.rstrip().rename_axis('OS').reset_index(name='System')
print (df1)
        OS                        System
0  Windows         Desktop Laptop Mobile
1    Linux  Desktop Laptop Mobile Tablet
2      Mac                         

解决方案DataFrame.melt也是可能的,只有在仅过滤Trues 和聚合之后,join还需要通过列名的唯一值添加已删除的类别(没有第一个):

df1 = (df.melt('System', var_name='OS')
         .query("value == True")
         .groupby('OS')['System']
         .agg(' '.join)
         .reindex(df.columns[1:].unique(), fill_value='')
         .rename_axis('OS')
         .reset_index(name='System'))

print (df1)
        OS                        System
0  Windows         Desktop Laptop Mobile
1    Linux  Desktop Laptop Mobile Tablet
2      Mac                                   

推荐阅读