与熊猫的相关矩阵的计算和可视化
-
16-10-2019 - |
题
我有一个带有几个条目的熊猫数据框架,我想计算某些商店的收入之间的相关性。有许多商店,具有收入数据,活动面积(戏剧,布料商店,食品...)和其他数据的分类。
我试图创建一个新的数据框架,并插入具有属于同一类别的各种商店的收入的列,而返回的数据框架仅填充了第一列,其余的则充满了NAN。我疲倦的代码:
corr = pd.DataFrame()
for at in activity:
stores.loc[stores['Activity']==at]['income']
我想这样做,所以我可以使用 .corr()
给出商店类别之间的相关矩阵。
之后,我想知道如何绘制矩阵值(-1比1,因为我想使用Pearson的相关性)与Matplolib。
解决方案
我建议在以下内容上进行某种游戏:
在此示例中使用UCI鲍鱼数据...
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Read file into a Pandas dataframe
from pandas import DataFrame, read_csv
f = 'https://archive.ics.uci.edu/ml/machine-learning-databases/abalone/abalone.data'
df = read_csv(f)
df=df[0:10]
df
相关矩阵绘图函数:
#相关矩阵绘图函数
def correlation_matrix(df):
from matplotlib import pyplot as plt
from matplotlib import cm as cm
fig = plt.figure()
ax1 = fig.add_subplot(111)
cmap = cm.get_cmap('jet', 30)
cax = ax1.imshow(df.corr(), interpolation="nearest", cmap=cmap)
ax1.grid(True)
plt.title('Abalone Feature Correlation')
labels=['Sex','Length','Diam','Height','Whole','Shucked','Viscera','Shell','Rings',]
ax1.set_xticklabels(labels,fontsize=6)
ax1.set_yticklabels(labels,fontsize=6)
# Add colorbar, make sure to specify tick locations to match desired ticklabels
fig.colorbar(cax, ticks=[.75,.8,.85,.90,.95,1])
plt.show()
correlation_matrix(df)
希望这可以帮助!
其他提示
另一种选择是使用Seaborn中的热图功能来绘制协方差。此示例使用R中的ISLR软件包中的自动数据集(与您显示的示例相同)。
import pandas.rpy.common as com
import seaborn as sns
%matplotlib inline
# load the R package ISLR
infert = com.importr("ISLR")
# load the Auto dataset
auto_df = com.load_data('Auto')
# calculate the correlation matrix
corr = auto_df.corr()
# plot the heatmap
sns.heatmap(corr,
xticklabels=corr.columns,
yticklabels=corr.columns)
如果您想变得更加幻想,可以使用 熊猫风格, , 例如:
cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)
def magnify():
return [dict(selector="th",
props=[("font-size", "7pt")]),
dict(selector="td",
props=[('padding', "0em 0em")]),
dict(selector="th:hover",
props=[("font-size", "12pt")]),
dict(selector="tr:hover td:hover",
props=[('max-width', '200px'),
('font-size', '12pt')])
]
corr.style.background_gradient(cmap, axis=1)\
.set_properties(**{'max-width': '80px', 'font-size': '10pt'})\
.set_caption("Hover to magify")\
.set_precision(2)\
.set_table_styles(magnify())
为什么不简单地这样做:
import seaborn as sns
import pandas as pd
data = pd.read_csv('Dataset.csv')
plt.figure(figsize=(40,40))
# play with the figsize until the plot is big enough to plot all the columns
# of your dataset, or the way you desire it to look like otherwise
sns.heatmap(data.corr())
你可以更改 调色板 通过使用 cmap
范围:
sns.heatmap(data.corr(), cmap='BuGn')