python-3.x - 熔化多个布尔列
问题描述
这个问题是这里已经问过的问题的扩展: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
列中的值由空格分隔。
解决方案
一个想法是首先将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
也是可能的,只有在仅过滤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
推荐阅读
- docker - 解码 Kubernetes 秘密
- php - 如何在 psysh 控制台中调用 php 函数?
- dygraphs - 不使用数据标签的 Dygraphs
- python - Matplotlib:避免注释和勾选 y_tick 标签重叠
- angular - 数据未发送到 FormGroup - Angular
- css - 为字体真棒图标设置固定尺寸
- javascript - 是否可以在不自动折叠/展开树的情况下替换具有数据树的表中的数据?
- javascript - 无法使用画布更改图像像素
- matlab - 如何修复“位置 1 中的索引超出数组范围”
- python - python中的海龟图形无法正常工作