Pandas 将 DataFrame 从 long-form 重新排列为 wide-form
Pandas rearrange DataFrame from long-form to wide-form
我找了一段时间但没有找到解决问题的方法...
我有一个具有以下结构的 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
我想要两个 headers .. 首先分隔国家,其次分隔属性 temp 和 dc。我的索引应该是 date_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.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
我找了一段时间但没有找到解决问题的方法...
我有一个具有以下结构的 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
我想要两个 headers .. 首先分隔国家,其次分隔属性 temp 和 dc。我的索引应该是 date_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.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