如何使用.corr()皮尔逊相关性获取DataFrame中两个选定列之间的相关性

时间:2019-03-13 16:29:23

标签: python pandas correlation

我正在使用大型DataFrame。但是我试图获得两列之间的相关性。我使用了以下代码:
corr_P=Top15['Energy Supply per Capita'].corr(Top15['Energy Supply per Capita'])

这给了我一个错误:
'sqrt' method is not available for 'float' type.

这是我必须使用的“ .corr()方法,(皮尔逊的相关性)”。

1 个答案:

答案 0 :(得分:0)

您可以按自己的方式指定列。我在同一数据集上尝试了您的代码,没有任何错误。我会对您使用的版本感到好奇。

此外,我假设您想查看2列(相同列)的相关性。如果运行该命令,它将给出正确的输出1

import pandas as pd
import numpy as np
import re
def split_it(line):
    line = re.split('(\d+)', line)
    return line[0]
def get_energy():
    energy = pd.read_excel('C:/Energy Indicators.xls', skiprows = 17, skip_footer = 38, parse_cols = range(2, 6), index_col = None, names = ["Country", "Energy Supply", "Energy Supply per Capita", "% Renewable"], na_values='...')
    energy['Energy Supply'] = energy['Energy Supply'] * 1000000
    energy['Country'] = energy["Country"].apply(split_it)
    energy = energy.replace ("Republic of Korea", "South Korea")
    energy = energy.replace("United States of America", "United States")
    energy = energy.replace('United Kingdom of Great Britain and Northern Ireland' , 'United Kingdom')
    energy = energy.replace('China, Hong Kong Special Administrative Region', 'Hong Kong')
    energy['Country'] = energy['Country'].apply(lambda x: re.sub(r'\(.*\)', '', x))
#     energy.Country = energy.Country.apply(lambda x: x.split(' (')[0])
    energy['Country'] = energy['Country'].map(lambda x: x.strip())
    return energy
Top15 = get_energy()


corr_P = Top15['Energy Supply per Capita'].corr(Top15['Energy Supply per Capita'])

输出:

print (corr_P)
1.0