Python 将数据帧转换为多索引列
我有这样一个数据帧:Python 将数据帧转换为多索引列,python,pandas,multi-index,Python,Pandas,Multi Index,我有这样一个数据帧: 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 i、 e.将每一列按名称和数字对分组,数字按过去用作索引的相应
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
i、 e.将每一列按名称和数字对分组,数字按过去用作索引的相应名称排序
我可以用一个循环来做,但我一直在想,一定有一个更“简单”的方法来做。这是我在上面使用的代码:
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
numpy的破折号
啊,这给了我一些思考的东西。第一种方法非常简洁,但它仍然涉及到在列中循环。第二种方法避免了这一点。谢谢
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
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