【问题标题】:Melt multiple boolean columns熔化多个布尔列
【发布时间】:2021-08-16 22:10:11
【问题描述】:

这个问题是这里已经提出的问题的延伸: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.x pandas dataframe


    【解决方案1】:

    一个想法是首先将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                                   
    

    【讨论】:

      【解决方案2】:

      这是另一个解决方案:

      df = df.melt(id_vars=['System'],var_name='OS')
      df.groupby('OS').agg(lambda x: ' '.join([e for i,e in enumerate(x) if df.loc[x.index[i],'value']]))
      

      【讨论】:

        猜你喜欢
        • 2019-01-02
        • 2013-08-03
        • 1970-01-01
        • 2010-12-05
        • 1970-01-01
        • 2020-01-11
        • 1970-01-01
        • 2021-10-05
        • 2020-02-06
        相关资源
        最近更新 更多