我的数据集
Name rate counts
A 10.3 3
B 15.4 9
C 21.9 11
D 9.11 4
E 2.21 5
F 7.7 21
G 18.9 20
H 55.1 41
数据集显示了不同名字的人的数量和比率。
我想知道比率与计数的相关性。
例如,如果计数很高,那么比率就高或低。
哪种方法适合显示两者之间的联系?
检查这个代码。
# import requires packages
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# read the data file
df = pd.read_csv('data.csv')
# calculate correlation matrix
corr = df.corr()
# prepare the plot
sns.heatmap(corr, annot = True, vmin = 0, vmax = 1)
# show the plot
plt.show()
它给了我以下的相关矩阵:
如你所见 rate
和 count
是相当高的。0.85
. 不过考虑到我只用了你上面报告的数据,只有8行,也许你应该用更高的样本来获得更可靠的结果。
你只需要使用Pandas函数来计算相关性。
df.rate.corr(df.counts)
它支持三种方法:"pearson"(默认),"kendall "和 "spearman"。更多细节请参考 此处.
你可以尝试用numpy得到两个变量之间的系数。
import numpy
a = [10.3, 15.4, 21.9, 9.11, 2.21, 7.7, 18.9, 55.1]
b = [3, 9, 11, 4, 5, 21, 20, 41]
print(numpy.corrcoef(a,b))
如果反对角线中的数值为正且接近1,那么它们之间的相关性就更大。
[[1. 0.84965646]
[0.84965646 1. ]]
系数值约为0.85。说明它们是正向高度相关的。