[英]python numpy split array into unequal subarrays
我正在嘗試將數組拆分為 n 個部分。 有時這些部分的尺寸相同,有時它們的尺寸不同。
我正在嘗試使用:
split = np.split(list, size)
當大小均分到列表中時,這可以正常工作,但否則會失敗。 有沒有辦法用額外的“少數”元素“填充”最終數組?
你在尋找 np.array_split 嗎? 這是文檔字符串:
Split an array into multiple sub-arrays.
Please refer to the ``split`` documentation. The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis.
See Also
--------
split : Split array into multiple sub-arrays of equal size.
Examples
--------
>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
[array([ 0., 1., 2.]), array([ 3., 4., 5.]), array([ 6., 7.])]
http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.array_split.html
def split_padded(a,n):
padding = (-len(a))%n
return np.split(np.concatenate((a,np.zeros(padding))),n)
簡短的方法:使用: numpy.array_split
而不是numpy.split
但最好的方法是使用部分拆分來拆分數組
def cs(chunksize, fs):
sa = []
num =chunksize
while(num< fs):
sa.append(num)
num += chunksize
sa.append(num+fs%chunksize)
return sa
將函數作為參數傳遞給 split
for chunk in np.split(df, cs(chunksize,fs)):
chunk.to_excel('{}/{}_{:02d}.xlsx'.format(output_folder,split_name, i), index=False)
i +=1
您可以通過將索引作為列表傳遞來將數組拆分為不相等的塊示例
**x = np.arange(10)**
x
(0,1,2,3,4,5,6,7,8,9)
np.array_split(x,[4])
[array([0,1,2,3],dtype = int64),
array([4,5,6,7,8,9],dtype = int64)**
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.