将 pandas 数据框转换为多索引列

Convert pandas dataframe to multi-index columns

我有一个这样的数据框:

     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

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

我可以用循环来完成,但我一直认为必须有更多 'pandasy' 的方法来完成。这是我在上面使用的代码:

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