【问题标题】:Pandas rearrange DataFrame from long-form to wide-form [duplicate]Pandas将DataFrame从长格式重新排列为宽格式[重复]
【发布时间】:2018-05-24 11:04:53
【问题描述】:

我一直在寻找,但我没有找到解决我的问题的方法......

我有一个具有以下结构的 csv:

date_time, country, temp, dc
2018-01-01 00:00:00, Germany, 12, 0
...
2018-01-01 00:00:00, Austria, 13, 3
...
2018-01-01 00:00:00, France, 4, 9
...

如您所见,date_time 会重复。

我想用python pandas得到如下结构:

|                     | Germany  | Austria  |  France
|                     | temp, dc | temp, dc | temp, dc
________________________________________________________
| 2018-01-01 00:00:00 | 12  , 0  | 13  , 3  | 4   , 9

我想要两个标题 .. 首先分隔国家,其次是属性 temp 和 dc。我的索引应该是 date_time 属性。

谢谢你的帮助!!!

【问题讨论】:

    标签: python pandas pivot pivot-table reshape


    【解决方案1】:

    这会给你你想要的:

    df.pivot_table(index='date_time', columns='country', values=['temp', 'dc']).swaplevel(axis=1).sort_index(axis=1)
    #country   Austria      France      Germany     
    #               dc temp     dc temp      dc temp
    #date_time                                      
    #1               3   13      9    4       0   12
    

    【讨论】:

    • 太棒了!非常感谢!!!
    • @zipa- 不错的答案
    【解决方案2】:

    试试这个,

    df =df.groupby('date_time').apply(lambda x:x.set_index(['date_time','country']).unstack()).swaplevel(axis=1).reset_index(level=1, drop=True)
    

    输出:

    country             Austria France Germany Austria France Germany
                           temp   temp    temp      dc     dc      dc
    date_time                                                        
    2018-01-01 00:00:00      13      4      12       3      9       0
    

    【讨论】:

    • 感谢您的回复!但是这个输出看起来不像我想要的 .. 属性和国家被交换了。为什么 date_time 加倍?我会尝试继续玩这个 .apply(lambda ...) 技术!谢谢!!
    • @khuesmann - 答案已更新
    猜你喜欢
    • 2015-08-04
    • 1970-01-01
    • 2016-07-12
    • 2013-03-18
    • 2021-10-26
    相关资源
    最近更新 更多