我有一堆股票数据,我正在尝试建立一个数据框,该数据框从相关矩阵中获取前两个股票和最后一个股票,以及它们的实际相关性。
让我们说矩阵corr
像这样:
A B C D E
A 1.00 0.65 0.31 0.94 0.55
B 0.87 1.00 0.96 0.67 0.41
C 0.95 0.88 1.00 0.72 0.69
D 0.64 0.84 0.99 1.00 0.78
E 0.71 0.62 0.89 0.32 1.00
我想要做的是能够返回最佳的两只,相关性最低的股票,以及它们与股票A,B,C,D和E的相关性,同时放弃每只股票必须与之明显的1.00相关性。本身。
结果数据框,或者最容易显示的数据框看起来像这样:
Stock 1st 1st_Val 2nd 2nd_Val Last Last_Val
A D 0.94 B 0.65 C 0.31
B C 0.96 A 0.87 E 0.41
C A 0.95 B 0.88 E 0.69
D C 0.99 B 0.84 A 0.64
E C 0.89 A 0.71 D 0.32
到目前为止,通过我的尝试,我能够使用corr[stock].nlargest().index[0:].tolist()
浏览并返回相关的股票名称,然后分别从[1]
,[2]
和[-1]
中选取列出并粘贴到字典中,然后从那里构建数据框。但是我无法返回相关值,而且我怀疑无论如何我都没有以最有效的方式这样做。
真的很感谢任何帮助,欢呼声
答案 0 :(得分:2)
您的条件很难概括为一个命令,但这是您可以采用的一种方法。
import numpy as np
np.fill_diagonal(corr.values, np.nan)
print(corr)
# A B C D E
#A NaN 0.65 0.31 0.94 0.55
#B 0.87 NaN 0.96 0.67 0.41
#C 0.95 0.88 NaN 0.72 0.69
#D 0.64 0.84 0.99 NaN 0.78
#E 0.71 0.62 0.89 0.32 NaN
您可以使用Find names of top-n highest-value columns in each pandas dataframe row上的答案来获取每一行(股票)的前2位和后1位值。
order_top2 = np.argsort(-corr.values, axis=1)[:, :2]
order_bottom = np.argsort(corr.values, axis=1)[:, :1]
result_top2 = pd.DataFrame(
corr.columns[order_top2],
columns=['1st', '2nd'],
index=corr.index
)
result_bottom = pd.DataFrame(
corr.columns[order_bottom],
columns=['Last'],
index=corr.index
)
result = result_top2.join(result_bottom)
# 1st 2nd Last
#A D B C
#B C A E
#C A B E
#D C B A
#E C A D
现在使用pandas.DataFrame.lookup
来获取corr
中每一列的result
中相应的列值
for x in result.columns:
result[x+"_Val"] = corr.lookup(corr.index, result[x])
print(result)
# 1st 2nd Last 1st_Val 2nd_Val Last_Val
#A D B C 0.94 0.65 0.31
#B C A E 0.96 0.87 0.41
#C A B E 0.95 0.88 0.69
#D C B A 0.99 0.84 0.64
#E C A D 0.89 0.71 0.32
print(result[['1st', '1st_Val', '2nd', '2nd_Val', 'Last', 'Last_Val']])
# 1st 1st_Val 2nd 2nd_Val Last Last_Val
#A D 0.94 B 0.65 C 0.31
#B C 0.96 A 0.87 E 0.41
#C A 0.95 B 0.88 E 0.69
#D C 0.99 B 0.84 A 0.64
#E C 0.89 A 0.71 D 0.32
答案 1 :(得分:1)
如果您需要可视化结果,但实际上并不需要获取和使用实际的相关值,那么为什么不使用非常简单的heatmap呢?您还可以使用该图来在每个正方形上显示数字。
import seaborn as sns
import pandas as pd
dict = {'Date':['2018-01-01','2018-01-02','2018-01-03','2018-01-04','2018-01-05'],'Col1':[1,2,3,4,5],'Col2':[1.1,1.2,1.3,1.4,1.5],'Col3':[0.33,0.98,1.54,0.01,0.99],'Col4':[8,9.98,6,0.01,0.1],'Col1':[19,42,3,0.4,51]}
df = pd.DataFrame(dict, columns=dict.keys())
sns.heatmap(df.corr())
答案 2 :(得分:1)
一个不同的答案更多地依赖于modern pandas style。对于第二大相关性,我找不到很好的解决方案。找到答案后,我将对其进行编辑。
### Create an example df
df = pd.DataFrame(data = {"A":pd.np.random.randn(10),
"B":pd.np.random.randn(10),
"C":pd.np.random.randn(10),
"D":pd.np.random.randn(10),
}
)
# Solution
(
df.corr() #correlation matrix
.replace(1, pd.np.nan) # replace the matrix with nans
.assign( # assign new variables
First = lambda x: x.loc[["A","B","C","D"], ["A","B","C","D"]].idxmax(axis = 1), # Biggest correlation idx
First_value = lambda x: x.loc[["A","B","C","D"], ["A","B","C","D"]].max(axis = 1), # Biggest correlation
Last = lambda x: x.loc[["A","B","C","D"],["A","B","C","D"]].idxmin(axis = 1), # Smallest correlation idx
Last_value = lambda x: x.loc[["A","B","C","D"],["A","B","C","D"]].idxmin(axis = 1), # Smallest correlation
)
)
我使用.loc[["A","B","C","D"],["A","B","C","D"]]
以便仅在未修改的数据帧上进行操作。
A B C D First First_value Last Last_value
A NaN -0.085776 -0.203110 -0.003450 D -0.003450 C C
B -0.085776 NaN -0.110402 0.687283 D 0.687283 C C
C -0.203110 -0.110402 NaN 0.017644 D 0.017644 A A
D -0.003450 0.687283 0.017644 NaN B 0.687283 A A
答案 3 :(得分:0)
corr.unstack().min()
-> 找到值
corr.unstack().idxmin()
-> 查找索引