首页 > 解决方案 > 熊猫宽到长两列

问题描述

我在 Python 中使用 pandas,并希望在折叠两列的同时将数据框从宽转换为长。具体来说,我有一个这样的数据框:

user   town    dog  cat
tom    london  1    1
dick   miami   0    1
harry  paris   0    0
tina   london  3    0
donna  dallas  0    1
hannah dallas  1    0

我想在折叠dogscats转换为一个类别时将其转换为长表pet

user   town    pets
tom    london  dog
tom    london  cat
dick   miami   cat
tina   london  dog
tina   london  dog
tina   london  dog
donna  dallas  cat
hannah dallas  dog

在 R 中,可以使用该函数执行此操作,pivot_long但我想学习如何使用 pandas 在 Python 中执行此操作。到目前为止,我已经尝试使用pandas.melt(df, id_vars=['user', 'town'], value_vars=['dog', 'cat']),但输出看起来像:

user   town   variable  value
tom    london dog       1
tom    london cat       1
dick   miami  dog       0
dick   miami  cat       1
...

标签: pythonpandas

解决方案


set_indexstack宠物列成一个系列。重命名列轴会将该名称带到结果中。然后使用Series.repeat您可以获得所需的副本,因为所有信息都在索引中。

s = df.set_index(['user', 'town']).rename_axis(columns='pets').stack()

#df1 = s.repeat(s).reset_index().drop(columns=0)

# Credit @Scott Boston for this simpler version.
df1 = s.repeat(s).index.to_frame(index=False)

print(df1)
     user    town pets
0     tom  london  dog
1     tom  london  cat
2    dick   miami  cat
3    tina  london  dog
4    tina  london  dog
5    tina  london  dog
6   donna  dallas  cat
7  hannah  dallas  dog

推荐阅读