Skip to main content
 首页 » 编程设计

python之将 Pandas 数据框转换为多索引列

2025年02月15日7leader

我有一个这样的数据框:

     a  b  c 
foo  1  6  9 
bar  2  4  8 
fud  3  5  7 

我想把它转换成这样:

     a        b        c     
  name num name num name num 
0  foo   1  bar   4  fud   7 
1  bar   2  fud   5  bar   8 
2  fud   3  foo   6  foo   9 

即将每一列分组为名称和数字对,数字按照对应的名称排序,这些名称曾经是索引。

我可以用循环来完成,但我一直认为必须有一种更“ Pandas ”的方式来做到这一点。这是我在上面使用的代码:

import pandas as pd 
 
my_index=['foo','bar','fud'] 
orig = pd.DataFrame({'a': [1,2,3], 'b':[6,4,5], 'c':[9,8,7]}, index=my_index) 
multi = pd.MultiIndex.from_product([['a','b','c'],['name','num']]) 
x = pd.DataFrame(index=range(3), columns=multi) 
 
for h in orig.columns: 
    s = orig[h].sort_values().reset_index() 
    x[h,'name'] = s['index'] 
    x[h,'num'] = s[h] 

不过,我确信有更好的方法可以做到这一点,所以如果 pandas 专家可以帮助我,我将不胜感激。

谢谢!

请您参考如下方法:

Pandas

def proc(s): 
    return s.sort_values().rename_axis('name').reset_index(name='num') 
 
pd.concat({j: proc(c) for j, c in df.iteritems()}, axis=1) 
 
     a        b        c     
  name num name num name num 
0  foo   1  bar   4  fud   7 
1  bar   2  fud   5  bar   8 
2  fud   3  foo   6  foo   9 

破折号 numpy

v = df.values 
a = v.argsort(0) 
r = np.arange(v.shape[1])[None, :] 
 
nums = pd.DataFrame(v[a, r], columns=df.columns) 
names = pd.DataFrame(df.index.values[a], columns=df.columns) 
 
pd.concat( 
    [names, nums], 
    axis=1, 
    keys=['names', 'nums'] 
).swaplevel(0, 1, 1).sort_index(1) 
 
     a        b        c     
  name num name num name num 
0  foo   1  bar   4  fud   7 
1  bar   2  fud   5  bar   8 
2  fud   3  foo   6  foo   9