python - 根据值拆分 Numpy 数组

标签 python numpy

假设我有这个 NumPy 数组:

a = np.array([0, 3, 5, 5, 0, 10, 14, 15, 56, 0, 12, 23, 45, 23, 12, 45, 
              0, 1, 0, 2, 3, 4, 0, 0 ,0])

我想打印 0 之间的所有数字并自动将它们添加到新的 np.array(见下文):

a1=[3, 5, 5]
a2=[10, 14, 15, 56]
a3=[12, 23, 45, 23, 12, 45]
a4=[1]
a5=[2, 3, 4]

是否有内置函数可以执行此操作?

最佳答案

这是使用 np.where 的矢量化方法和 np.split -

idx = np.where(a!=0)[0]
aout = np.split(a[idx],np.where(np.diff(idx)!=1)[0]+1)

sample 运行-

In [23]: a
Out[23]: 
array([ 0,  3,  5,  5,  0, 10, 14, 15, 56,  0,  0,  0, 12, 23, 45, 23, 12,
       45,  0,  1,  0,  2,  3,  4,  0,  0,  0])

In [24]: idx = np.where(a!=0)[0]

In [25]: np.split(a[idx],np.where(np.diff(idx)!=1)[0]+1)
Out[25]: 
[array([3, 5, 5]),
 array([10, 14, 15, 56]),
 array([12, 23, 45, 23, 12, 45]),
 array([1]),
 array([2, 3, 4])]

关于python - 根据值拆分 Numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38277182/

相关文章:

python - 无法启动 Airflow worker/flower,需要澄清 Airflow 架构以确认安装正确

python - numpy.where() 具有 3 个或更多条件

python - 我有一个带有两个独立离散变量的高斯函数。如何创建所有可能值的矩阵?

python - 我怎样才能得到一个模型的相关对象和模型的 child 的相关对象的总数?

python - 将任意长度的字典项展平为 Python 中的路径列表

python - timedelta 操作的错误结果

python - 在 numpy 中创建一个新数组,以不同的多样性选择性地复制旧数组的行

python - np.array() 和 np.asarray() 有什么区别?

python - pytest 的错误

python - python 列表中每个月的工作日