【问题标题】:Insert new columns into numpy array将新列插入 numpy 数组
【发布时间】:2018-04-10 14:04:24
【问题描述】:

我在 python 中有一个 numpy 数组,名为 my_values,大小为 5x5,还有一个 numpy 向量,其中包含大小为 1x90(5 False,85 True)naned cols_indexes 的布尔值。我想扩展我的初始数组my_values,在等于False 的cols_indexes 的位置索引中使用零。因此,最后我的转换矩阵my_values 的大小应该为 5x90(85 个新列填充为零)。一个使用数组而不是布尔向量的简单示例是:

def insert_one_per_row(arr, mask, putval):

   mask_ext = np.column_stack((mask, np.zeros((len(mask), 1), dtype=bool)))
   out = np.empty(mask_ext.shape, dtype=arr.dtype)
   out[~mask_ext] = arr.ravel()
   out[mask_ext] = putval
   return out

y = np.arange(25).reshape(5, 5)
x = np.array([[False,  True,  False, False, False],
          [False,  True,  False, False, False],
          [False,  True,  False, False, False],
          [False,  True,  False, False, False],
          [False,  True,  False, False, False]], dtype=bool)

arr = insert_one_per_row(y, x, putval=0)

此示例适用于布尔数组。但是在我的情况下,x 是一个向量而不是一个数组。 x 包含 True 用于我需要添加的位置的新列和 False 用于最终数组位置的现有列。如何使用向量 x 而不是矩阵 x 插入新列?

【问题讨论】:

  • stackoverflow.com/questions/5064822/… 结论是周围有方法,但最好从一个尽可能大的数组开始,并根据需要填写值。
  • 在我的情况下有必要做相反的事情,因为我需要处理没有零的矩阵。
  • 发生了。像docs.scipy.org/doc/numpy/reference/generated/… 这样的堆栈函数是否无法满足您的需求?
  • 您的问题可能有误?您写道,您希望在“等于 False 的 cols_indexes 的位置索引”中使用零,但有 5 个 False,而不是 85 个。
  • 是的,我的意思正好相反。我编辑了问题。

标签: python arrays numpy


【解决方案1】:

您的输入 - 调整到工作:

In [73]: y = np.arange(1,21).reshape(5, 4)
    ...: x = np.array([[False,  True,  False, False, False],
    ...:           [False,  True,  False, False, False],
    ...:           [False,  True,  False, False, False],
    ...:           [False,  True,  False, False, False],
    ...:           [False,  True,  False, False, False]], dtype=bool)
    ...:           

整个数组掩码,大致是你的函数做了什么

In [74]: res = np.full(x.shape, 0)    # assign the putval on creation
In [75]: res[~x] = y.ravel()
In [76]: res
Out[76]: 
array([[ 1,  0,  2,  3,  4],
       [ 5,  0,  6,  7,  8],
       [ 9,  0, 10, 11, 12],
       [13,  0, 14, 15, 16],
       [17,  0, 18, 19, 20]])

我们可以使用where 从一维掩码中获取列索引,这里是x 的行:

In [77]: res[:, np.where(~x[0,:])[0]]
Out[77]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12],
       [13, 14, 15, 16],
       [17, 18, 19, 20]])

assignment - 但不要使用 ravel,因为 RHS 是 (4,5)。此索引不会像完整的布尔掩码那样展平数组:

In [80]: res[:, np.where(~x[0,:])[0]] = 2*y
In [81]: res
Out[81]: 
array([[ 2,  0,  4,  6,  8],
       [10,  0, 12, 14, 16],
       [18,  0, 20, 22, 24],
       [26,  0, 28, 30, 32],
       [34,  0, 36, 38, 40]])

【讨论】:

    猜你喜欢
    • 2022-08-03
    • 2022-12-21
    • 2021-02-01
    • 2015-08-24
    • 1970-01-01
    • 2019-12-07
    • 2011-10-25
    • 2019-06-14
    • 1970-01-01
    相关资源
    最近更新 更多