Python Pandas将数据帧从长格式重新排列为宽格式
我找了一段时间,但没有找到解决问题的方法 我有一个具有以下结构的csv:Python Pandas将数据帧从长格式重新排列为宽格式,python,pandas,pivot,pivot-table,reshape,Python,Pandas,Pivot,Pivot Table,Reshape,我找了一段时间,但没有找到解决问题的方法 我有一个具有以下结构的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 ... | | Germany | Austria | France |
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
...
| | Germany | Austria | France
| | temp, dc | temp, dc | temp, dc
________________________________________________________
| 2018-01-01 00:00:00 | 12 , 0 | 13 , 3 | 4 , 9
如您所见,日期和时间将重复
我想使用python获得以下结构:
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
...
| | Germany | Austria | France
| | temp, dc | temp, dc | temp, dc
________________________________________________________
| 2018-01-01 00:00:00 | 12 , 0 | 13 , 3 | 4 , 9
我想要两个标题。。首先区分国家,其次是属性temp和dc。我的索引应该是date\u time属性
谢谢你的帮助 试试这个
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
试试这个
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
这将为您提供您想要的:
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
这将为您提供您想要的:
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
谢谢回复!但是这个输出看起来不像我想要的。。属性和国家/地区被交换。为什么约会时间增加了一倍?我会继续玩下去。运用(lambda…)技术!谢谢@库斯曼-回答更新谢谢回答!但是这个输出看起来不像我想要的。。属性和国家/地区被交换。为什么约会时间增加了一倍?我会继续玩下去。运用(lambda…)技术!谢谢@库斯曼-回答更新了!非常感谢@zipa-很好的回答太棒了!非常感谢@zipa-很好的回答