【问题标题】:Numpy replacing specific column index per row by using a list of indexes with nanNumpy 通过使用带有 nan 的索引列表替换每行的特定列索引
【发布时间】:2023-03-10 05:26:01
【问题描述】:

我正在尝试以下方法:

a = np.array([[1,2,3], [4,5,6], [7,8,9]])

print a
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

a[np.arange(len(a)), [1,0,2]] = 20 #--Code1

print a
array([[ 1, 20,  3],
       [20,  5,  6],
       [ 7,  8, 20]])

但是,如果我的索引中有nan

a[np.arange(len(a)), [1,np.nan,2]] = 20  #--Code2

它出错了。

我试图做的是,如果索引中存在nan,请不要更改任何内容。

即我想在上面实现Code2,以便获得以下内容:

    array([[ 1, 20,  3],
           [4,  5,  6],
           [ 7,  8, 20]])

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    使用masking -

    m = ~np.isnan(idx) # Mask of non-NaNs
    row = np.arange(a.shape[0])[m]
    col = idx[m].astype(int)
    a[row, col] = 20
    

    其中,idx 是索引数组。

    示例运行 -

    In [161]: a = np.array([[1,2,3], [4,5,6], [7,8,9]])
    
    In [162]: idx = np.array([1,np.nan,2])
    
    In [163]: m = ~np.isnan(idx) # Mask of non-NaNs
         ...: row = np.arange(a.shape[0])[m]
         ...: col = idx[m].astype(int)
         ...: a[row, col] = 20
         ...: 
    
    In [164]: a
    Out[164]: 
    array([[ 1, 20,  3],
           [ 4,  5,  6],
           [ 7,  8, 20]])
    

    【讨论】:

      猜你喜欢
      • 2014-06-19
      • 2021-10-06
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 2016-04-15
      • 2012-11-14
      • 2018-12-14
      • 2011-11-06
      相关资源
      最近更新 更多