2016-07-05 48 views
1

我試圖規範化一些數據。在我的數據框中,如果列以相同的前綴開頭,它們屬於一起(屬於ab_000ab_001,但ac_000不屬於前兩者)。所以我試圖用歸一化歸一化歸屬列。對於這一點,我已經寫了:Python - 評估字符串匹配時的類型錯誤

def normalize(df): 
    data = df.copy() 
    to_work_with = [] 
    for i in range(0, len(data.columns) - 1): 
     for j in range(0, len(data.columns) -1): 
      if data.columns[i][:2] == data.columns[j][:2]: # error here 
       to_work_with.append(data.columns[j]) 
     data[to_work_with] = nr(data[to_work_with],axis=1, norm='l1') 
     to_work_with = [] 
    return data 

然而,在註釋標明的路線,我得到一個錯誤:

TypeError: 'int' object has no attribute '__getitem__' 

如果我只是運行

data.columns[1][:2] == data.columns[2][:2] 

它返回一個False,沒有錯誤。我錯過了什麼?

[編輯] 在產生錯誤之前運行一段時間。通過比較之前增加一個print(data.columns[j][:2])正確的,我得到的輸出:

enter image description here

的樣本數據:

aa_000 ab_000 ac_000 ad_000 ae_000 af_000 af_001 af_002 af_003 af_004 ... ed_004 ed_005 ed_006 ed_007 ed_008 ed_009 ee_000 ef_000 eg_000 classN 
0 76698 NaN 2.130706e+09 280.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 493384.0 721044.0 469792.0 339156.0 157956.0 73224.0 0.0 0.0 0.0 -1 
1 33058 NaN 0.000000e+00 NaN 0.0 0.0 0.0 0.0 0.0 0.0 ... 178064.0 293306.0 245416.0 133654.0 81140.0 97576.0 1500.0 0.0 0.0 -1 
2 41040 NaN 2.280000e+02 100.0 0.0 0.0 0.0 0.0 0.0 0.0 ... 159812.0 423992.0 409564.0 320746.0 158022.0 95128.0 514.0 0.0 0.0 -1 
+2

你確定所有這些列是集合,而不是'int's?嘗試在提供錯誤的行之前插入'print(data.columns [j] [:2])'。 – SuperBiasedMan

+1

是的,我是積極的,它甚至會運行一段時間。我會用照片更新帖子。 –

+0

你能否向我們提供一個在函數中處理的數據樣本? – Jaxian

回答

0

它看起來像你的data.columns之一是int類型。

getitem()在使用operator []時被調用。

例如,當調用tmp = columns[2],columns.__getitem__(2)時。