【问题标题】:Group categories by IDs python按 ID 分组类别 python
【发布时间】:2018-10-04 19:39:57
【问题描述】:

我有一个表格(数据框)如下

--------------------------
|ID    | code  | happened|
--------------------------
|  1   | A     |    1    |
|  1   | B     |    1    |
|  1   | A     |    1    |
|  2   | A     |    0    |
|  2   | c     |    0    |
|  2   | D     |    0    |
|  3   | E     |    1    |
|  3   | E     |    1    |

happened 不会更改为 ID

--------------------------    
|ID    |  list | happened |
---------------------------
| 1    |  A,B,A| 1        |
| 2    | A,C,D | 0        |
| 3    | E, E  | 1        |

list 应该保持代码列表的顺序。非常感谢任何帮助

【问题讨论】:

    标签: python python-3.x pandas dataframe data-structures


    【解决方案1】:

    使用agg

    df.groupby('ID',as_index=False).agg({'code': lambda x : ','.join(x),'happened':'first'})
    Out[911]: 
       ID   code  happened
    0   1  A,B,A         1
    1   2  A,c,D         0
    2   3    E,E         1
    

    【讨论】:

    • 太棒了!有效! lambds x : 是什么意思?
    • @Sai 就像一个自定义函数
    【解决方案2】:

    一种使用pivot_table的方法:

    (df.pivot_table(
        index='ID', values='code', aggfunc=','.join).join(df.groupby('ID').happened.first()))
    

         code  happened
    ID
    1   A,B,A         1
    2   A,c,D         0
    3     E,E         1
    

    【讨论】:

    • 你的和另一个相似,但pivot_table
    猜你喜欢
    • 2019-09-06
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多