pandas 将列拆分为多级 [英] Pandas Split columns into multilevel

查看:73
本文介绍了 pandas 将列拆分为多级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据框:

I have a dataframe like this :

df = pd.DataFrame(pd.DataFrame([[1,2,3,4],[5,6,7,8],[9,10,11,12]],columns=["X_a","Y_b","X_b","Y_a"]))

   X_a  Y_b  X_b  Y_a
0    1    2    3    4
1    5    6    7    8
2    9   10   11   12

现在,我基本上是如何通过基于_(下划线)拆分列并根据首字母大写对它们进行分组来创建具有多级列的数据框的方法.在上述数据帧上进行这种转换的示例可以是:

Now I basically what to create a dataframe with multilevel columns by splitting the columns based on _ (underscore) and grouping them based on the initial Alphabet in capital. An example of this transformation on the above dataframe can be this :

     X         Y
     a    b    a    b
0    1    3    4    2
1    5    7    8    6
2    9   11   12   10

我尝试搜索解决方案,但最接近的是这个答案,不能完全解决我的问题.因此,除了强行提取列,然后拆分列并最终将它们排列在一起的暴力方式之外,Pandas中还有其他有效或快速的方法吗?任何帮助将不胜感激.

I tried searching for a solution but the closest I got was this answer, which does not solve my problem exactly. So, is there any efficient or quicker way to do this in Pandas besides the brute force way of extracting the columns, then splitting them and finally arranging them together ? Any help would be appreciated.

推荐答案

就地

df.columns = df.columns.str.split('_', expand=True)
df.sort_index(axis=1)

   X       Y    
   a   b   a   b
0  1   3   4   2
1  5   7   8   6
2  9  11  12  10


内联
不更改原始


Inline
Not altering the original

pd.DataFrame(
    df.values, columns=df.columns.str.split('_', expand=True)).sort_index(1)

   X       Y    
   a   b   a   b
0  1   3   4   2
1  5   7   8   6
2  9  11  12  10

这篇关于 pandas 将列拆分为多级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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