首页 > 解决方案 > Numpy基于除法拆分成数组

问题描述

我想要一些可以拆分一维数组的东西:

np.array([600, 400, 300, 600, 100, 0, 2160])

根据一个值(例如 500)进入二维数组,这样生成的数组应该看起来像

500 | 100 | 0   | 0   | 0   
400 | 0   | 0   | 0   | 0   
300 | 0   | 0   | 0   | 0   
500 | 100 | 0   | 0   | 0   
100 | 0   | 0   | 0   | 0   
0   | 0   | 0   | 0   | 0   
500 | 500 | 500 | 500 | 160

我们从左边填写可能有多少个 500,最后一个作为提醒。

我正在考虑使用 np.divmod() 但不知道如何构造数组本身。

标签: pythonarraysnumpy

解决方案


这是一个最小/最大问题而不是除法。

import numpy as np

arr = np.array([600, 400, 300, 600, 100, 0, 2160 ])    
res = np.zeros( (7, 6), dtype = np.int64)
res[:] = arr[:,None]

res -= np.arange( 0, 3000, 500 ) # Subtract successive 500s from arr.

res = np.clip( res, 0, 500 ) # Clip results to lie >= 0 and <= 500

res 

# array([[500, 100,   0,   0,   0,   0],
#        [400,   0,   0,   0,   0,   0],
#        [300,   0,   0,   0,   0,   0],
#        [500, 100,   0,   0,   0,   0],
#        [100,   0,   0,   0,   0,   0],
#        [  0,   0,   0,   0,   0,   0],
#        [500, 500, 500, 500, 160,   0]])

或作为一个班轮

np.clip( arr[:,None] - np.arange(0,3000,500), 0, 500 )

在下面疯狂物理学家的评论之后,一个更一般的功能

def steps_of( arr, step ):
    temp = arr[:, None] - np.arange( 0, step * ( arr.max() // step + 1), step)
    return np.clip( temp, 0, step )


    

推荐阅读