2017-07-28 25 views
0

我有三列小時,因素(影響停車場),ParkingSpaces.I能夠繪製相關矩陣,但它是所有組合之間的計算相關性,我想顯示所有5個不同文件的一個相關矩陣,但這些列之間的相關性只要。如何僅使用python爲特定列組合創建相關矩陣?

Correlation Matrix

import numpy as np 
import pandas as pd 
import seaborn as sns 
import math 
import matplotlib.pyplot as plt 
%matplotlib inline 
sns.set(style="darkgrid") 

Creche_Holiday =pd.read_csv("D:\Data Analysis\Practicum\DCU car parking data\New folder\Creche_Holiday.csv") 
Creche_Reading = pd.read_csv("D:\Data Analysis\Practicum\DCU car parking data\New folder\Creche_Reading.csv") 
Creche_Study = pd.read_csv("D:\Data Analysis\Practicum\DCU car parking data\New folder\Creche_Study.csv") 
Creche_Working = pd.read_csv("D:\Data Analysis\Practicum\DCU car parking data\New folder\Creche_Working.csv") 
Creche_Exam = pd.read_csv("D:\Data Analysis\Practicum\DCU car parking data\New folder\Creche_Exam.csv") 


catted = pd.concat([d.reset_index(drop=True) for d in [Creche_Working,Creche_Holiday,Creche_Reading,Creche_Study,Creche_Exam]], 
        axis=1, keys=['Working','Holiday', 'Reading', 'Study','Exam']) 

catted = catted.rename_axis(['Creche', 'Parking'], axis=1) 

corrmat = catted.corr() 
# Generate a mask for the upper triangle 
mask = np.zeros_like(corrmat, dtype=np.bool) 
mask[np.triu_indices_from(mask)] = True 
# Set up the matplotlib figure 
f, ax = plt.subplots(figsize=(12, 11)) 

# Generate a custom diverging colormap 
cmap = sns.diverging_palette(220,10,as_cmap=True) 

#sns.heatmap(corrmat, vmax=.3, center=0,square=True, linewidths=.5, cbar_kws={"shrink": .5}) 
# Draw the heatmap with the mask and correct aspect ratio 
sns.heatmap(corrmat,fmt=".2g",annot=True,cmap=cmap,linewidths=1,cbar=True,vmin=0, vmax=1,center=0,mask=mask) 

回答

0

您可以使用數據框的drop方法都放棄你不希望在你的熱圖繪製的行和列。

請考慮以下數據幀,其中只有兩列需要繪製。

df = pd.DataFrame(np.array([[1,2,3,4,5],[5,4,3,2,1],[3,5,6,7,8],[1,2,3,4,5]]).T) 
df.columns = ['Value','column_to_drop','Stuff','other_column_to_drop'] 

此數據框中的結果。

Value column_to_drop Stuff other_column_to_drop 
1 5 3 1 
2 4 5 2 
3 3 6 3 
4 2 7 4 
5 1 8 5 

很顯然我們希望從最終熱圖中刪除column_to_dropother_column_to_drop

要做到這一點,你需要運行下面的代碼。首先再次創建相關矩陣。在創建相關矩陣後,我們從相關矩陣的行和列中刪除column_to_drop和other_column_to_drop。

corr_df=df.corr() 
heatmap_df=corr_df.drop(['column_to_drop','other_column_to_drop']).drop(['column_to_drop','other_column_to_drop'],axis=1) 

然後,我們可以簡單地在這個最終的數據框上創建熱圖。

sns.heatmap(heatmap_df) 

產生這個熱圖。 enter image description here

您當然可以在繪圖之前選擇在heatmap_df上執行任何其他步驟。就像創建一個掩碼不要繪製兩次相同的值一樣。

+0

非常感謝,它幫助了我。 –

+0

它幫助你解決問題嗎?還是你仍然有問題?如果你仍然有問題,我可以編輯我的答案。 – error