如何从包含非数字列的数据框中计算相关性。

huangapple go评论103阅读模式
英文:

How to calculate corr from a dataframe with non-numeric columns

问题

我有以下数据集:

如何从包含非数字列的数据框中计算相关性。

这些数据属于宝可梦数据集:
https://elitedatascience.com/wp-content/uploads/2022/07/Pokemon.csv

我想绘制如下的热力图:

  1. # 计算相关性
  2. corr = stats_df.corr()
  3. # 热力图
  4. plt.figure(figsize=(9,8))
  5. sns.heatmap(corr)

但我得到了下面的错误;我该如何解决它?

如何从包含非数字列的数据框中计算相关性。

英文:

I have these data set as shown below:

如何从包含非数字列的数据框中计算相关性。

which belong to Pokemon dataset
https://elitedatascience.com/wp-content/uploads/2022/07/Pokemon.csv

I want to plot the heatmap as shown below:

  1. # Calculate correlations
  2. corr = stats_df.corr()
  3. # Heatmap
  4. plt.figure(figsize=(9,8))
  5. sns.heatmap(corr)

But I get this error below; how can I solve it?

如何从包含非数字列的数据框中计算相关性。

答案1

得分: 1

要计算(Pearson)相关性,您需要具有数值数据。

尝试:

  1. df = pd.read_csv('Pokemon.csv', encoding='latin1', index_col='#')
  2. corr = df.select_dtypes('number').drop(columns=['Total', 'Generation']).corr()
  3. sns.heatmap(data=corr)
  4. plt.tight_layout()
  5. plt.show()

输出:

  1. >>> corr
  2. HP Attack Defense Sp. Atk Sp. Def Speed
  3. HP 1.000000 0.422386 0.239622 0.362380 0.378718 0.175952
  4. Attack 0.422386 1.000000 0.438687 0.396362 0.263990 0.381240
  5. Defense 0.239622 0.438687 1.000000 0.223549 0.510747 0.015227
  6. Sp. Atk 0.362380 0.396362 0.223549 1.000000 0.506121 0.473018
  7. Sp. Def 0.378718 0.263990 0.510747 0.506121 1.000000 0.259133
  8. Speed 0.175952 0.381240 0.015227 0.473018 0.259133 1.000000

如何从包含非数字列的数据框中计算相关性。

英文:

To compute the (Pearson) correlation you need to have numeric data.

Try:

  1. df = pd.read_csv('Pokemon.csv', encoding='latin1', index_col='#')
  2. corr = df.select_dtypes('number').drop(columns=['Total', 'Generation']).corr()
  3. sns.heatmap(data=corr)
  4. plt.tight_layout()
  5. plt.show()

Output:

  1. >>> corr
  2. HP Attack Defense Sp. Atk Sp. Def Speed
  3. HP 1.000000 0.422386 0.239622 0.362380 0.378718 0.175952
  4. Attack 0.422386 1.000000 0.438687 0.396362 0.263990 0.381240
  5. Defense 0.239622 0.438687 1.000000 0.223549 0.510747 0.015227
  6. Sp. Atk 0.362380 0.396362 0.223549 1.000000 0.506121 0.473018
  7. Sp. Def 0.378718 0.263990 0.510747 0.506121 1.000000 0.259133
  8. Speed 0.175952 0.381240 0.015227 0.473018 0.259133 1.000000

如何从包含非数字列的数据框中计算相关性。

huangapple
  • 本文由 发表于 2023年6月12日 02:07:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76451866.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定