2013-11-10 95 views
4

我的numpy數組中的第三列是Age。在本專欄中,大約75%的條目是有效的,25%是空白的。第2列是性別,並使用一些操作,我計算出我的數據集中男性的平均年齡爲30歲。我的數據集中女性的平均年齡爲28.在numpy數組中替換空格

我想將男性的所有空白年齡值替換爲爲30,女性爲所有空白年齡值是28

但是我似乎無法做到這一點。任何人有建議或知道我做錯了什麼?

這裏是我的代碼:

# my entire data set is stored in a numpy array defined as x 

ismale = x[::,1]=='male' 
maleAgeBlank = x[ismale][::,2]=='' 
x[ismale][maleAgeBlank][::,2] = 30 

不管什麼時候,我與上面的代碼完成的原因,我鍵入x顯示該數據集的空白仍然存在,即使我將它們設置爲30。請注意,我不能做x[maleAgeBlank],因爲該列表將包含一些女性數據點,因爲女性數據點尚未排除。

有什麼辦法得到我想要的?由於某種原因,如果我做x[ismale][::,1] = 1(將'male'列設置爲1),那可行,但x[ismale][maleAgeBlank][::,2] = 30不起作用。

樣本陣列的:

#output from typing x 
array([['3', '1', '22', ..., '0', '7.25', '2'], 
    ['1', '0', '38', ..., '0', '71.2833', '0'], 
    ['3', '0', '26', ..., '0', '7.925', '2'], 
    ..., 
    ['3', '0', '', ..., '2', '23.45', '2'], 
    ['1', '1', '26', ..., '0', '30', '0'], 
    ['3', '1', '32', ..., '0', '7.75', '1']], 
    dtype='<U82') 

#output from typing x[0] 

array(['3', '1', '22', '1', '0', '7.25', '2'], 
    dtype='<U82') 

注意,我已經改變第2欄是男性0女性和1已經在上面的輸出

+0

你可以張貼陣列的樣品? – moenad

+0

@void現在添加。 –

回答

1

如何:

my_data = np.array([['3', '1', '22', '0', '7.25', '2'], 
        ['1', '0', '38', '0', '71.2833', '0'], 
        ['3', '0', '26', '0', '7.925', '2'], 
        ['3', '0', '', '2', '23.45', '2'], 
        ['1', '1', '26', '0', '30', '0'], 
        ['3', '1', '32', '0', '7.75', '1']], 
        dtype='<U82') 

ismale = my_data[:,1] == '0' 
missing_age = my_data[:, 2] == '' 
maleAgeBlank = missing_age & ismale 
my_data[maleAgeBlank, 2] = '30' 

結果:

>>> my_data 
array([[u'3', u'1', u'22', u'0', u'7.25', u'2'], 
     [u'1', u'0', u'38', u'0', u'71.2833', u'0'], 
     [u'3', u'0', u'26', u'0', u'7.925', u'2'], 
     [u'3', u'0', u'30', u'2', u'23.45', u'2'], 
     [u'1', u'1', u'26', u'0', u'30', u'0'], 
     [u'3', u'1', u'32', u'0', u'7.75', u'1']], 
     dtype='<U82') 
+0

完美!謝謝,非常乾淨和可以理解。甚至沒有想到「操作」。 –

1

可以使用where功能:

arr = array([['3', '1', '22', '1', '0', '7.25', '2'], 
      ['3', '', '22', '1', '0', '7.25', '2']], 
      dtype='<U82') 

blank = np.where(arr=='') 

arr[blank] = 20 

array([[u'3', u'1', u'22', u'1', u'0', u'7.25', u'2'], 
     [u'3', u'20', u'22', u'1', u'0', u'7.25', u'2']], 
     dtype='<U82') 

如果您想更改特定列,您可以執行以下操作:

male = np.where(arr[:, 1]=='') # where 1 is the column 
arr[male] = 30 

female = np.where(arr[:, 2]=='') # where 2 is the column 
arr[female] = 28 
+0

'where'是有效的,但目前的解決方案不檢查行的性別值並更改所有空白,而不僅僅是年齡列中的那些。 – ASGM

+0

他不想將年齡的空白值更改爲平均值嗎?年齡層的男性和女性只有1和2。所以他只需要兩個「哪裏」。 – moenad

0

您可以嘗試以更簡單的方式遍歷數組。這不是最有效的解決方案,但它應該完成工作。

for row in range(len(x)): 
    if row[2] == '': 
     if row[1] == 1: 
      row[2] == 30 
     else: 
      row[2] == 28 
+0

使用帶有numpy數組的循環稱爲無意義。通過迭代你放鬆了numpy的優點。 – moenad

+0

@void這很公平。我並不是說沒有更好的解決方案。但如果所有OP關心的是快速解決這個特殊任務,希望這會有所幫助。 – ASGM

+0

使用'where'更有效率。檢查我的答案。 – moenad