这个问题是这里已经问过的问题的扩展:在熊猫的单个列中熔化多个布尔列
如果数据看起来像:
| 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
列中的值由空格分隔。
一个想法是首先将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
解决方案 withDataFrame.melt
也是可能的,只有在只过滤True
s 和聚合之后,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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句