3 回答

TA貢獻1801條經(jīng)驗 獲得超16個贊
實現(xiàn)此目的的一種方法是創(chuàng)建一個新數(shù)組,然后將其連接起來。例如,假設這M
當前是您的數(shù)組。
您可以將 col(1)^2 計算為C = M[:,0] ** 2
(我將其解釋為第 1 列的平方,而不是第 1 列的第二列中的值的冪)。C
現(xiàn)在將是一個形狀為 (100, ) 的數(shù)組,因此我們可以使用它來重塑它,C = np.expand_dims(C, 1)
這將創(chuàng)建一個長度為 1 的新軸,因此我們的新列現(xiàn)在具有形狀 (100, 1)。這很重要,因為我們希望所有兩個數(shù)組在連接時都具有相同的維數(shù)。
這里的最后一步是使用連接它們np.concatenate
??偟膩碚f,我們的結果看起來像這樣
C = M[:, 0] ** 2 C = np.expand_dims(C, 1) M = np.concatenate([M, C], axis=1) #third row will now be col(1) ^ 2
如果你是那種喜歡一字排開做事的人,你有:
M = np.concatenate([M, np.expand_dims(M[:, 0] ** 2, 0)], axis=1)
話雖這么說,我建議看看Pandas,在我看來,它更自然地支持這些操作。在熊貓中,這將是
M["your_col_3_name"] = M["your_col_1_name"] ** 2
其中 M 是 pandas 數(shù)據(jù)框。

TA貢獻1868條經(jīng)驗 獲得超4個贊
# generate an array with shape (100,2), fill with 2.
a = np.full((100,2),2)
# calcuate the square to first column, this will be a 1-d array.
squared=a[:,0]**2
# concatenate the 1-d array to a,
# first need to convert it to 2-d arry with shape (100,1) by reshape(-1,1)
c = np.concatenate((a,squared.reshape(-1,1)),axis=1)

TA貢獻1842條經(jīng)驗 獲得超13個贊
附加 axis=1 應該可以。
a = np.zeros((5,2))
b = np.ones((5,1))
print(np.append(a,b,axis=1))
這應該返回:
[[0,0,1],
[0,0,1],
[0,0,1],
[0,0,1],
[0,0,1]]
添加回答
舉報