我有一个像这样的列的数据框(例如,1是任何值来简化这里的事情:
ID App R1 Pear R1 Oro R1 App R2 Pear R2 Oro R2 App R3 Pear R3 Oro R3
0 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1
我想重新排列这样的列:
ID App R1 App R2 App R3 Pear R1 Pear R2 Pear R3 Oro R1 Oro R2 Oro R3
0 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1
我试过了:
df.columns = [['ID'] + ['App R{}'.format(r+1)] + ['Pear R{}'.format(r+1)] + ['Matched fragment ions R{}'.format(r+1)] + ['Oro R{}'.format(r+1)] for r in range(len(files))]
n.b:App,Pear和Oro的数量r将取决于我开始的csv的数量r
然而,到目前为止没有成功。
谢谢你能帮我解决这个问题。
答案 0 :(得分:4)
将自定义sorted
与查找密钥
In [4291]: look = {'I':0, 'A':1, 'P':2, 'O':3} # order for letters
In [4292]: sorted(df.columns, key=lambda x: look.get(x[0], '')) # first letter key
Out[4292]:
['ID',
'App R1',
'App R2',
'App R3',
'Pear R1',
'Pear R2',
'Pear R3',
'Oro R1',
'Oro R2',
'Oro R3']
In [4293]: df[sorted(df.columns, key=lambda x: look.get(x[0], ''))]
Out[4293]:
ID App R1 App R2 App R3 Pear R1 Pear R2 Pear R3 Oro R1 Oro R2 \
0 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
Oro R3
0 1
1 1
答案 1 :(得分:1)
我认为MultiIndex
应该有所帮助:
#set all not R columns to index
df = df.set_index(['ID'])
#create multiindex
df.columns = df.columns.str.split(expand=True)
#custom reordering
df = df.reindex(columns=['App','Pear','Oro'], level=0)
print (df)
App Pear Oro
R1 R2 R3 R1 R2 R3 R1 R2 R3
ID
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
df.columns = df.columns.map(' '.join)
print (df)
App R1 App R2 App R3 Pear R1 Pear R2 Pear R3 Oro R1 Oro R2 Oro R3
ID
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1