【问题标题】:Replace all instances of a character in a 2d numpy array [duplicate]替换二维numpy数组中字符的所有实例[重复]
【发布时间】:2021-07-22 06:41:20
【问题描述】:

我有一个像这样的 Numpy 数组:

   [[ a, b, c]
    [ d, d, e]
    [ d, f, g ]]  

如何在保持数组形状的同时替换此二维数组中的每个 char d 实例?假设 temp 是我们的 2d 数组,我尝试了这个,但它不起作用:

for i in range(len(temp)):
        temp[i].replace('d','')

【问题讨论】:

  • 请提供minimal reproducible example。不要偷懒。
  • @juanpa.arrivillaga 我认为 OP 已经提供了一个 MRE。由于显而易见的原因,尝试的代码没有运行,但是恕我直言,这已经足够了。

标签: python numpy


【解决方案1】:

假设 temp 是一个 numpy 数组,尝试使用索引更新

temp[temp=='d'] = ''

【讨论】:

    【解决方案2】:

    您可以在布尔索引上使用切片并设置值。

    import numpy as np
    
    x = np.array([[ 'a', 'b', 'c'],
        [ 'd', 'd', 'e'],
        [ 'd', 'f', 'g' ]]
    )
    
    x[x=='d'] = 'z'
    

    【讨论】:

      猜你喜欢
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 2017-02-25
      • 2011-01-08
      • 1970-01-01
      • 2021-08-16
      相关资源
      最近更新 更多