如何重塑此数据框 [英] How to reshape this dataframe
问题描述
我需要像这样重塑数据框:
I need to reshape the dataframe like this:
nam code date1 date2
0 a 1 1/1 1/2
1 b 3 3/4 4/5
但是df.stack
在这种情况下似乎没用.
but df.stack
seems useless in this situation.
所需的输出:
nam code date
0 a 1 1/1
1 a 1 1/2
2 b 3 3/4
3 b 3 4/5
推荐答案
您可以使用lreshape
, reindex_axis
列和最后一个
You can use lreshape
, sort_values
by column nam
, reindex_axis
columns and last reset_index
:
print pd.lreshape(df, {'date': ['date1', 'date2']})
.sort_values('nam')
.reindex_axis(['nam','code','date'], axis=1)
.reset_index(drop=True)
nam code date
0 a 1 1/1
1 a 1 1/2
2 b 3 3/4
3 b 3 4/5
使用 melt
的另一种解决方案, drop
用于删除列sort_values
按列nam
和最后一个 reset_index
:
Another solution with melt
, drop
for droping column variable
, sort_values
by column nam
and last reset_index
:
print pd.melt(df, id_vars=['nam','code'], value_name='date')
.drop('variable', axis=1)
.sort_values('nam')
.reset_index(drop=True)
nam code date
0 a 1 1/1
1 a 1 1/2
2 b 3 3/4
3 b 3 4/5
lreshape
现在没有文档记录,但将来有可能会被删除(与pd一起使用.也是).
可能的解决方案是将所有3个功能合并为一个-也许是melt
,但现在尚未实现.也许是在一些新版本的熊猫中.然后我的答案将被更新.
Possible solution is merging all 3 functions to one - maybe melt
, but now it is not implementated. Maybe in some new version of pandas. Then my answer will be updated.
这篇关于如何重塑此数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!