[英]How can I create a mapping between two dataframes to calculate spearman's correlation?
我有一个示例 dataframe 将水果映射到颜色:
Fruit Colour
Olive Purple
Apple Green
Berry red
然后我有两个数字数据框
Olive Apple Berry
4 3 0
9 3 8
1 6 5
Purple Red Green
56 45 23
19 48 35
20 19 26
如何根据映射找到列之间的 spearman 相关性? 即橄榄和紫色、苹果和绿色、浆果和红色之间的相关性?
我知道要找到两列之间的相关性,我可以使用以下内容:
df['Some_Column'].corr(df['Some_Other_Column'])
数据帧的可重现代码:
mapping_dataframe = {'Fruit': ['Olive', 'Apple', 'Berry'], 'Colour': ['Purple', 'Green', 'Red']}
fruit_dataframe={'Olive': [4,9,1], 'Apple': [3,3,6], 'Berry':[0,8,5]}
colour_dataframe={'Purple':[56,19,20], 'Red':[45,48,19], 'Green':[23,35,26]}
为此,您可以使用 [ scipy][1]
的Spearman Rank Correlation
实现。
下面是一个例子。 请注意,我必须将您的输入数据更改为矩阵(即pandas dataframe
或numpy.ndarray
)
from scipy.stats import spearmanr
import pandas as pd
import seaborn as sns, matplotlib.pyplot as plt
# Code provided by OP, edited
mapping_dataframe = {'Fruit': ['Olive', 'Apple', 'Berry'], 'Colour': ['Purple', 'Green', 'Red']}
fruit_dataframe=pd.DataFrame.from_dict({'Olive': [4,9,1], 'Apple': [3,3,6], 'Berry':[0,8,5]})
colour_dataframe=pd.DataFrame.from_dict({'Purple':[56,19,20], 'Red':[45,48,19], 'Green':[23,35,26]})
correlation, p_value = spearmanr(fruit_dataframe, colour_dataframe)
print(correlation)
plt.figure(figsize=(10,8))
sns.heatmap(correlation, vmin=-1, vmax=1, annot=True).set(title="Correlation Heatmap")
plt.show()
产生:
[ 1. -0.8660254 0.5 -0.5 1. 0.5 ]
[-0.8660254 1. 0. 0. -0.8660254 0. ]
[ 0.5 0. 1. -1. 0.5 1. ]
[-0.5 0. -1. 1. -0.5 -1. ]
[ 1. -0.8660254 0.5 -0.5 1. 0.5
和
将两个concat
连接在一起并计算所有组合的相关性。 然后切片上四分之一,以获得所有水果与所有颜色的相关性。 最后,使用映射 DataFrame 来索引堆叠的相关矩阵。
import pandas as pd
df = pd.concat([pd.DataFrame(fruit_dataframe), pd.DataFrame(colour_dataframe)],
axis=1, keys=['fruit', 'colour'])
# fruit colour
# Olive Apple Berry Purple Red Green
#0 4 3 0 56 45 23
#1 9 3 8 19 48 35
#2 1 6 5 20 19 26
s = df.corr().xs('fruit', axis=0).xs('colour', axis=1).stack()
#Olive Purple -0.166294
# Red 0.840414
# Green 0.812240
#Apple Purple -0.479317
# Red -0.995567
# Green -0.277350
#Berry Purple -0.937114
# Red -0.049132
# Green 0.911293
#dtype: float64
dfm = pd.DataFrame(mapping_dataframe)
s.loc[dfm.set_index(['Fruit', 'Colour']).index]
Fruit Colour
Olive Purple -0.166294
Apple Green -0.277350
Berry Red -0.049132
dtype: float64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.