简体   繁体   English

如何将 pivot 行转换为 pandas 中的列

[英]how to pivot rows to columns in pandas

I have a table in csv format that looks like this.我有一个 csv 格式的表格,看起来像这样。 I would like to pivot column.我想pivot列。

UserId Date category part_of_day Frequency duration_max

 1      2020-09-10  System tool     evening         1   3.436
 1      2020-09-11  Calendar        afternoon       5   5.313
 1      2020-09-11  Calendar         night          3   2.760
 1      2020-09-11  Clock            night          2   0.418
 1      2020-09-11  Communication   afternoon       35  59.936
50      2020-08-15  Communication        night      7   26.591
50      2020-08-15  Phone_and_SMS       morning     7   17.359
50      2020-08-15  Productivity        morning     4   45.751
50      2020-08-15  Productivity         night      2   5.832
`

I would like the end result to like like this:我希望最终结果像这样:

UserId   date         System tool    Calendar   Clock  Communication Phone_and_SMS    Productivity               
 1    2020-09-10         1             nan       nan          nan      nan               nan
 1    2020-09-11         nan            5         2           35       nan               nan
 
 50   2020-08-15         nan            nan       nan        nan        7                 7                 

I have tried this code: df.pivot_table(df,values = 'Frequency',index=['UserId'], columns = 'category')我试过这段代码: df.pivot_table(df,values = 'Frequency',index=['UserId'], columns = 'category')

Use df.pivot_table with aggfunc='first' :df.pivot_tableaggfunc='first'一起使用:

In [2383]: df.pivot_table(index=['UserId', 'Date'], columns='category', values='Frequency', aggfunc='first')
Out[2383]: 
category           Calendar  Clock  Communication  Phone_and_SMS  Productivity  System tool
UserId Date                                                                                
1      2020-09-10       NaN    NaN            NaN            NaN           NaN          1.0
       2020-09-11       5.0    2.0           35.0            NaN           NaN          NaN
50     2020-08-15       NaN    NaN            7.0            7.0           4.0          NaN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM