2017-02-20 78 views
3

我正在使用熊貓/ numpy使用1400x1400相關矩陣,我的目標是刪除使用給定變量名稱的行和列。每行和每列有變量的名稱和這兩個變量之間的相關性:使用python刪除矩陣中相應的行/列

  abandon abhorrent abominable 
abandon  1.00 0.12  0.10 
abhorrent 0.12 1.00  0.99 
abominable 0.10 0.99  1.00 

爲數據幀轉換爲我用as_matrix矩陣:

datafile = pd.read_csv('data.csv') 
df_matrix = datafile.as_matrix 

我無法理解如何創建一個新的數據框,而不包括例如變量「放棄」(即,刪除與「放棄」相對應的列和行)。

首先,我試圖嘗試只選擇一列得到的我怎麼可能會創建的,我想變量列表的理解:

df_matrix = datafile.as_matrix(columns=['abhorrent']) 

然而,這僅返回數組和我失去所有的行/列名稱。

我也嘗試刪除導入數據後的行/列。這需要我花費額外的步驟來形成我不想要的變量名稱列表,然後將它們作爲列/行號傳遞,但這似乎是可行的。我不知道這個代碼是完全正確的但是:

df_matrix2 = np.delete(df_matrix, 1, axis=0) 
df_matrix2 = np.delete(df_matrix, 1, axis=1) 

此代碼,據我所知,沒有產生新基質的任何變化。它仍然是一個1400x1400矩陣。

回答

2

您可以使用DataFrame.drop()方法:

In [9]: df 
Out[9]: 
      abandon abhorrent abominable 
abandon  1.00  0.12  0.10 
abhorrent  0.12  1.00  0.99 
abominable  0.10  0.99  1.00 

In [10]: df.drop('abandon', 1).drop('abandon') 
Out[10]: 
      abhorrent abominable 
abhorrent  1.00  0.99 
abominable  0.99  1.00 
1

這裏有一個具有行山坳索引 -

In [32]: df 
Out[32]: 
      abandon abhorrent abominable 
abandon  1.00  0.12  0.10 
abhorrent  0.12  1.00  0.99 
abominable  0.10  0.99  1.00 

In [33]: strg = 'abandon' 

In [34]: df.iloc[df.index!=strg, df.columns!=strg] 
Out[34]: 
      abhorrent abominable 
abhorrent  1.00  0.99 
abominable  0.99  1.00