获得相关矩阵的唯一组合值-熊猫

时间:2018-08-09 19:27:16

标签: python pandas correlation

假设我有一个如下所示的相关矩阵:

df = pd.DataFrame(data={'a':[1,0.2,0.3,0.4],'b':[0.2,1,0.5,0.6],'c':[0.3,0.5,1,0.7],'d':[0.4,0.6,0.7,1]}, index=['a','b','c','d'])

提取每种成对组合(a-b,a-c等)​​的唯一值的最佳方法是什么?

df2 =
      a_b  a_c  a_d  b_c  b_d  c_d 
      0.2  0.3  0.4  0.5  0.6  0.7

我看到的唯一方法是编写自己的函数,但想知道是否有人知道此操作的快捷方式

3 个答案:

答案 0 :(得分:8)

IIUC:

df_out = df.stack()
df_out.index = df_out.index.map('_'.join)
df_out = df_out.to_frame().T

输出:

   a_a  a_b  a_c  a_d  b_a  b_b  b_c  b_d  c_a  c_b  c_c  c_d  d_a  d_b  d_c  
0  1.0  0.2  0.3  0.4  0.2  1.0  0.5  0.6  0.3  0.5  1.0  0.7  0.4  0.6  0.7   

而且,如果您想摆脱a_a,b_b等。

df_out = df.stack()
df_out = df_out[df_out.index.get_level_values(0) != df_out.index.get_level_values(1)]
df_out.index = df_out.index.map('_'.join)
df_out = df_out.to_frame().T

输出

   a_b  a_c  a_d  b_a  b_c  b_d  c_a  c_b  c_d  d_a  d_b  d_c
0  0.2  0.3  0.4  0.2  0.5  0.6  0.3  0.5  0.7  0.4  0.6  0.7

或者摆脱b_a并保留a_b:

df_out = df.stack()
df_out = df_out[df_out.index.get_level_values(0) < df_out.index.get_level_values(1)]
df_out.index = df_out.index.map('_'.join)
df_out = df_out.to_frame().T

或在.loc中使用lambda函数合并几行:

df_out = df.stack().loc[lambda x: x.index.get_level_values(0) < x.index.get_level_values(1)]
df_out.index = df_out.index.map('_'.join)
df_out = df_out.to_frame().T

输出:

   a_b  a_c  a_d  b_c  b_d  c_d
0  0.2  0.3  0.4  0.5  0.6  0.7

答案 1 :(得分:3)

IIUC,您可以使用索引

df2 = df.unstack().reset_index()
s = df2[['level_0', 'level_1']].agg(frozenset,1).drop_duplicates()
df2 = df2.loc[s.index]
ind = df2.agg(lambda k:  (k['level_0']+'_'+k['level_1']), axis=1)
df2.set_index(ind)[0].to_frame().T

    a_a a_b a_c a_d b_b b_c b_d c_c c_d d_d
0   1.0 0.2 0.3 0.4 1.0 0.5 0.6 1.0 0.7 1.0

答案 2 :(得分:0)

您可以有效地使用矩阵:

import numpy as np
df = pd.DataFrame(data={'a':[1,0.2,0.3,0.4],'b':[0.2,1,0.5,0.6],'c':[0.3,0.5,1,0.7],'d':[0.4,0.6,0.7,1]}, index=['a','b','c','d'])
unique_values=[s for s in np.tril(df, k=-1).flatten() if s!=0]
print(unique_values)

它给你:[0.2, 0.3, 0.5, 0.4, 0.6, 0.7]

关键是 np.tril 函数。