将pandas数据框从宽转换为长 [英] Convert pandas dataframe from wide to long

查看:166
本文介绍了将pandas数据框从宽转换为长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 pandas.Dataframe 以下几列:

I have a pandas.Dataframe with the following columns:

a_1  ab_1  ac_1    a_2   ab_2   ac_2
2      3     4      5     6      7 

如何将其转换为以下内容?

How do I convert it into the following?

a    ab    ac 
2     3     4
5     6     7 

我试图用pandasmelt从宽格式转换为长格式,但不确定语法.

I was trying to use pandas melt to convert from wide to long format, but not sure of the syntax.

推荐答案

您可以使用

You can use split for MultiIndex and then reshape by stack and last use reset_index for remove MultiIndex:

df.columns = df.columns.str.split('_', expand=True)
df = df.stack().reset_index(drop=True)
print (df)
   a  ab  ac
0  2   3   4
1  5   6   7


df = df.stack().reset_index(level=0, drop=True)
print (df)
   a  ab  ac
1  2   3   4
2  5   6   7

这篇关于将pandas数据框从宽转换为长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆