gpt4 book ai didi

python - 在 numpy 中沿一个轴对数据进行分箱

转载 作者:太空狗 更新时间:2023-10-29 18:08:33 32 4
gpt4 key购买 nike

我有一个大的二维数组 arr,我想使用 numpy 在第二个轴上装箱。因为 np.histogram 展平了我当前正在使用 for 循环的数组:

import numpy as np

arr = np.random.randn(100, 100)

nbins = 10
binned = np.empty((arr.shape[0], nbins))

for i in range(arr.shape[0]):
binned[i,:] = np.histogram(arr[i,:], bins=nbins)[0]

我觉得在 numpy 中应该有一种更直接、更有效的方法来做到这一点,但我没有找到。

最佳答案

你可以使用 np.apply_along_axis :

x = np.array([range(20), range(1, 21), range(2, 22)])

nbins = 2
>>> np.apply_along_axis(lambda a: np.histogram(a, bins=nbins)[0], 1, x)
array([[10, 10],
[10, 10],
[10, 10]])

主要优点(如果有的话)是它稍微短一些,但我不希望性能有太大提升。它在组装每行结果时可能稍微更有效。

关于python - 在 numpy 中沿一个轴对数据进行分箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40018125/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com