簡體   English   中英

如何在多索引pandas數據框中選擇嵌套列

[英]How to select nested columns in a multi-indexed pandas dataframe

我創建了一個像這樣的3D Pandas數據幀:

A=  ['ECFP', 'ECFP', 'ECFP', 'FCFP', 'FCFP', 'FCFP', 'RDK5', 'RDK5', 'RDK5']

B = ['R', 'tau', 'RMSEc', 'R', 'tau', 'RMSEc', 'R', 'tau', 'RMSEc']

C = array([[ 0.1 ,  0.3 ,  0.5 ,   nan,  0.6 ,  0.4 ],
       [ 0.4 ,  0.3 ,  0.3 ,   nan,  0.4 ,  0.3 ],
       [ 1.2 ,  1.3 ,  1.1 ,   nan,  1.5 ,  1.  ],
       [ 0.4 ,  0.3 ,  0.4 ,  0.8 ,  0.1 ,  0.2 ],
       [ 0.2 ,  0.3 ,  0.3 ,  0.3 ,  0.5 ,  0.6 ],
       [ 1.  ,  1.2 ,  1.  ,  0.9 ,  1.2 ,  1.  ],
       [ 0.4 ,  0.7 ,  0.5 ,  0.4 ,  0.6 ,  0.6 ],
       [ 0.6 ,  0.5 ,  0.3 ,  0.3 ,  0.3 ,  0.5 ],
       [ 1.2 ,  1.5 ,  1.3 ,  0.97,  1.5 ,  1.  ]])

df = pd.DataFrame(data=C.T, columns=pd.MultiIndex.from_tuples(zip(A,B)))
df = df.dropna(axis=0, how='any')

最終的Dataframe如下所示:

  ECFP            FCFP            RDK5           
     R  tau RMSEc    R  tau RMSEc    R  tau RMSEc
0  0.1  0.4   1.2  0.4  0.2   1.0  0.4  0.6   1.2
1  0.3  0.3   1.3  0.3  0.3   1.2  0.7  0.5   1.5
2  0.5  0.3   1.1  0.4  0.3   1.0  0.5  0.3   1.3
4  0.6  0.4   1.5  0.1  0.5   1.2  0.6  0.3   1.5
5  0.4  0.3   1.0  0.2  0.6   1.0  0.6  0.5   1.0

如何才能在所有類型的數據('ECFP','FCFP','RDK5')的'R'值之間獲得相關矩陣?

使用IndexSlice

In [53]: df.loc[:, pd.IndexSlice[:, 'R']]
Out[53]:
  ECFP FCFP RDK5
     R    R    R
0  0.1  0.4  0.4
1  0.3  0.3  0.7
2  0.5  0.4  0.5
4  0.6  0.1  0.6
5  0.4  0.2  0.6

通過使用slice

df.loc[:,(slice(None),'R')]
Out[375]: 
  ECFP FCFP RDK5
     R    R    R
0  0.1  0.4  0.4
1  0.3  0.3  0.7
2  0.5  0.4  0.5
4  0.6  0.1  0.6
5  0.4  0.2  0.6

這兩個答案都有效,但首先我必須lexstort,否則我會收到此錯誤:

KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (2), lexsort depth (1)'

解決方案是:

df.sortlevel(axis=1, inplace=True)
print "Correlation matrix of Pearson's R values among all feature vector types:"
df.loc[:, pd.IndexSlice[:, 'R']].corr()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM