【问题标题】:How to conditionally assign values to multi-dimensional arrays?如何有条件地为多维数组赋值?
【发布时间】:2018-02-08 02:28:42
【问题描述】:
#T.shape=(10L,1L)
C=np.zeros((len(T),4)) 
C[T==label1]==[1,1,1,1]
C[T==label2]==[2,2,2,2]

得到错误:

布尔索引与维度 1 的索引数组不匹配;维度为 4,但对应的布尔维度为 1

我打算根据对应的T值将“=”右侧的4个值分配给C的每一行。我该怎么做?

【问题讨论】:

  • 应该colsC
  • 是的,对不起。会更新
  • 试试C[T.ravel() == label1, :] = [1,1,1,1]
  • 保罗,它奏效了。谢谢你。 -杰斯

标签: python arrays numpy indexing


【解决方案1】:

函数numpy.where 可以做到这一点。

T = np.array([['A','B','A','A'],['B','C','A','B']])
C = np.zeros(T.shape)
C[np.where(T == 'A')] = 1
print(C)

应该打印

[[1. 0. 1. 1.]
 [0. 0. 1. 0.]]

【讨论】:

    猜你喜欢
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 2021-06-17
    • 2023-03-17
    相关资源
    最近更新 更多