我剛剛開始使用 numpy 陣列和熊貓資料幀,我正在做一個練習專案,但遇到了一些問題。我有一個熊貓資料框,我將它的行傳遞給一個函式來做一些作業。該函式接受兩個不同的陣列,一個標記為最佳和最差,然后創建一個新向量來比較總和。從那里它將回傳 pandas.apply 已經傳遞的當前陣列,或者它將回傳基于 sum() 最低的新向量。這將創建一個新的 python 陣列,它最終需要是一個 20x5 的矩陣。該函式作業正常,但回傳的資料幀需要轉換為大小為 (20 x 5) 的 python 陣列以進行進一步的作業,當呼叫 np.array() 時,它將其轉換為大小為 (20,) 的陣列. 我想只使用 .reshape(20, 5) 會作業,因為它有足夠的元素可以使用,但它不會,它只是在運行時失敗。感謝任何幫助,因為我找不到任何可以幫助我理解為什么會發生這種情況的東西。
(錯誤,正如許多人通過閱讀上面可以猜到的,是:“無法將大小為 20 的陣列重塑為形狀 (20,5)”)
除了顯示它的程式之外的代碼(可以自己運行):
import numpy as np
import pandas as pd
rng = np.random.default_rng(seed=22)
df = pd.DataFrame(rng.random((20,5)))
def new_vectors(current, best, worst):
#convert current to numpy array
current = current.to_numpy()
#construct a new vector to check
new = np.add(current, np.subtract((rng.random()*(np.subtract(best, np.absolute(current)))), ((rng.random()*(np.subtract(worst, np.absolute(current)))))))
#get the new sum for the new and old vectors
summed = current.sum()
newsummed = new.sum()
#return the smallest one
return np.add(((newsummed < summed)*(new)), ((newsummed > summed)*(current))).flatten()
z = np.array(df.apply(new_vectors, args=(df.iloc[0].to_numpy(), df.iloc[11].to_numpy()), axis=1))
z.reshape(20,5) #I know reshape() creates a copy, just here to show it doesn't work regardless
uj5u.com熱心網友回復:
您的原始資料框 - 出于顯示目的而減少長度:
In [628]: df = pd.DataFrame(rng.random((4,5)))
In [629]: df
Out[629]:
0 1 2 3 4
0 0.891169 0.134904 0.515261 0.975586 0.150426
1 0.834185 0.671914 0.072134 0.170696 0.923737
2 0.065445 0.356001 0.034787 0.257711 0.213964
3 0.790341 0.080620 0.111369 0.542423 0.199517
下一幀:
In [631]: df1=df.apply(new_vectors, args=(df.iloc[0].to_numpy(), df.iloc[3].to_numpy()), axis=1)
In [632]: df1
Out[632]:
0 [0.891168725430691, 0.13490384333565053, 0.515...
1 [0.834184861872087, 0.6719141503303373, 0.0721...
2 [0.065444520313796, 0.35600115939269394, 0.034...
3 [0.7903408924058509, 0.08061955595765169, 0.11...
dtype: object
請注意,它有 1 列,其中包含陣列。從中創建一個陣列:
In [633]: df1.to_numpy()
Out[633]:
array([array([0.89116873, 0.13490384, 0.51526113, 0.97558562, 0.15042584]),
array([0.83418486, 0.67191415, 0.07213404, 0.17069617, 0.92373724]),
array([0.06544452, 0.35600116, 0.03478695, 0.25771129, 0.21396367]),
array([0.79034089, 0.08061956, 0.1113691 , 0.54242262, 0.19951741])],
dtype=object)
即 (4,) 物件資料型別。該 dtype 很重要。即使元素本身都有 5 個元素,reshape也不能跨越“物件”邊界。我們無法將其重塑為 (4,5)。
但是我們可以使用concatenate這些陣列:
In [636]: np.vstack(df1.to_numpy())
Out[636]:
array([[0.89116873, 0.13490384, 0.51526113, 0.97558562, 0.15042584],
[0.83418486, 0.67191415, 0.07213404, 0.17069617, 0.92373724],
[0.06544452, 0.35600116, 0.03478695, 0.25771129, 0.21396367],
[0.79034089, 0.08061956, 0.1113691 , 0.54242262, 0.19951741]])
uj5u.com熱心網友回復:
您可以手動進行重塑。
洗掉
z.reshape(20,5)。這不適用于陣列陣列。應用函式后,改用這個:
# Create a empty matrix with desired size matrix = np.zeros(shape=(20,5)) # Iterate over z and assign each array to a row in the numpy matrix. for i,arr in enumerate(z): matrix[i] = arr
如果您不知道矩陣所需的大小。將矩陣創建為matrix = np.zeros(shape=df.shape)。
使用的所有代碼:
import numpy as np
import pandas as pd
rng = np.random.default_rng(seed=22)
df = pd.DataFrame(rng.random((20,5)))
def new_vectors(current, best, worst):
#convert current to numpy array
current = current.to_numpy()
#construct a new vector to check
new = np.add(current, np.subtract((rng.random()*(np.subtract(best, np.absolute(current)))), ((rng.random()*(np.subtract(worst, np.absolute(current)))))))
#get the new sum for the new and old vectors
summed = current.sum()
newsummed = new.sum()
#return the smallest one
return np.add(((newsummed < summed)*(new)), ((newsummed > summed)*(current))).flatten()
z = np.array(df.apply(new_vectors, args=(df.iloc[0].to_numpy(), df.iloc[11].to_numpy()), axis=1))
matrix = np.zeros(shape=df.shape)
for i,arr in enumerate(z):
matrix[i] = arr
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/369776.html
