先解釋下什么叫數據的相關性:
計算兩個數組的平均值,如果兩個數組中的兩個值都大於平均值或者都小於平均值,則得到true. 如果一個大於平均值一個小於平均值,則得到false.最后計算true和false的個數.
比如,兩個數組[1, 2, 3, 4] and [4, 5, 6, 7] , 得到 (4, 0). 因為 1 和 4 都低於他們所在數組的平均值, 2 和 5 也都低於他們所在數組的平均值, 3 和 6 都高於他們所在數組的平均值, 4 和 7 也都高於他們所在數組的平均值.所以計算結果為true的有4個,false的為0.
如果數組是[1, 2, 3, 4] and [7, 6, 5, 4], 那結果就是 (0, 4). 因為 1 低於他所在數組的平均值而 7 高於們所在數組的平均值, 其它幾項也類似...
一個栗子:
比如有如下數據,20個城市的人均壽命和城市的gdp,計算壽命和gdp的相關性就是,計算是否壽命較高的城市,gdp也會較高,壽命較低,gdp也較低...就是說,gdp和壽命,是否相關...如果計算得到的true比較多,那就是表示是相關的,如果得到的false比較多,那就表示不相關.
countries = ['Albania', 'Algeria', 'Andorra', 'Angola', 'Antigua and Barbuda', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan', 'Bolivia'] life_expectancy_values = [74.7, 75. , 83.4, 57.6, 74.6, 75.4, 72.3, 81.5, 80.2, 70.3, 72.1, 76.4, 68.1, 75.2, 69.8, 79.4, 70.8, 62.7, 67.3, 70.6] gdp_values = [ 1681.61390973, 2155.48523109, 21495.80508273, 562.98768478, 13495.1274663 , 9388.68852258, 1424.19056199, 24765.54890176, 27036.48733192, 1945.63754911, 21721.61840978, 13373.21993972, 483.97086804, 9783.98417323, 2253.46411147, 25034.66692293, 3680.91642923, 366.04496652, 1175.92638695, 1132.21387981]
life_expectancy = pd.Series(life_expectancy_values)
gdp = pd.Series(gdp_values)
# 計算相關性的函數
def variable_correlation(pd_1, pd_2): pd_1_mean = pd_1.mean() pd_2_mean = pd_2.mean()
# 都高於平均值或都低於平均值的,得到true,一個高一個低的,得到false
result_series = ((pd_1 > pd_1_mean) & \ (pd_2 > pd_2_mean)) | \ ((pd_1 < pd_1_mean) & \ (pd_2 < pd_2_mean))
# 計算true的個數 num_same_direction = result_series.sum() # 計算false的個數
num_different_direction = len(result_series) - num_same_direction return (num_same_direction,num_different_direction) print(variable_correlation(life_expectancy,gdp))
# 結果
(17,3)
說明壽命和gdp是相關的.