python - 熊猫宽到长两列
问题描述
我在 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
我想在折叠dogs
并cats
转换为一个类别时将其转换为长表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
...
解决方案
set_index
和stack
宠物列成一个系列。重命名列轴会将该名称带到结果中。然后使用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
推荐阅读
- java - 遍历 div 中的页面链接,然后单击包含 Selenium (java) 中特定值的每个链接
- python - 有没有办法使用 MQTT 增加网络摄像头输出的 FPS?
- javascript - 如何添加不同的
到火库? - css - HTML5 内嵌视频忽略 z-index
- c++ - 使用 C++ 从文件中读取数据
- java - Spring Batch 应用程序失败,没有任何错误消息
- php - 在 Woocommerce 上处理产品类型
- php - 为什么 PHP 在我的 HTML 中间放一个随机数?
- javascript - 在 React 钩子中切换对象状态内的值的正确方法是什么?
- c - Cs50 pset1 积分