python - 在python中从一维数组和 bool 数组创建一个二维数组

标签 python numpy

你好,我正在尝试从这些数组创建一个二维数组

A=[5, 7, 1, -3, 0, 2, 2, 7, 10, 11, -1, 8, 5, 18, 9]

B=[False, False, True, True, True, False, True, True, False, False, False, True, False, True, True]

我希望得到这样的矩阵

C= [[1, -3, 0],
    [2, 7],
    [8],
    [18,9]]

也就是说,每次将数组 B 从 False 更改为 True 时,都会创建一个包含连续 True 值的新行。

请有人帮助我

最佳答案

常规整数 NumPy 数组不能具有锯齿状形状,例如对于二维数组,每行必须具有相同的列数。但是您可以通过 np.split 创建数组列表:

lst_of_array = np.split(A, np.where(np.diff(B) == 1)[0]+1)[{0:1,1:0}[B[0]]::2]

# [array([ 1, -3,  0]),
#  array([2, 7]),
#  array([8]),
#  array([18,  9])]

或者对于列表列表:

from operator import methodcaller

lst_of_lst = list(map(methodcaller('tolist'), lst_of_array))

# [[1, -3, 0],
#  [2, 7],
#  [8],
#  [18, 9]]

关于python - 在python中从一维数组和 bool 数组创建一个二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54048128/

相关文章:

python - numpy 数组行主要和列主要

python - python tarfile 中 tar --strip 的等效功能,用于随机命名的子文件夹

python - 外键问题

python - Groupby 与 TimeGrouper 'backwards'

python - Numba 矩阵向量乘法

python - 将ndarray从float64转换为整数

python - 如何使用 numpy.vectorize 或 numpy.frompyfunc

python - try/except 不捕获特定类型的异常

python - 在 Python 3 中使用带字节的 textwrap.dedent()

python - 使用 Zeroconf/PyBonjour 在 Python 中读/写字符串