python - 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() 但不知道如何构造数组本身。
解决方案
这是一个最小/最大问题而不是除法。
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 )
推荐阅读
- jquery - 如何使用 Jquery 为 FB Tracking Pixel 提取 url 查询
- html - HTML 标记的替换示例
- java - 在 java 项目中加载 cacerts 时出错 - 原因:java.security.InvalidAlgorithmParameterException:trustAnchors 参数必须非空
- javascript - 使用颜色、百分比和度数输入在 vue 中手动创建径向网格
- javascript - 如何在节点中上传最大 1gb 的文件 - nginx
- ms-access - 按天分组列 - DAX
- java - 我在我的 Firestore DB 文档中添加了一个地图作为一个字段,里面有一个子字段,我的 RecyclerView 遇到了问题
- node.js - 如何使用 Supbase 向另一个身份验证提供程序进行身份验证?
- clojure - 为什么 (map (fn [f] (f 0)) `(inc)) 在 Clojure 中返回 (nil)
- powershell - 读取主机 PowerShell 中的输出变量属性值