【问题标题】:Change some of numpy array columns according to logical condition根据逻辑条件更改一些numpy数组列
【发布时间】:2016-11-15 10:25:16
【问题描述】:

我有一个2DNumPy数组,我想执行以下操作:

对于数组中的每一列,即一系列非递减值,将这一列替换为差异列(即每个条目是前两个条目之间的差异)。

其他每一列都保持不变(除了第一行被删除以适应差异列维度)。

例如在矩阵中:

[ [1,1,1,2,3,4]
  [1,3,4,3,4,5]
  [1,7,3,4,2,7] ]

差异矩阵为:

[ [0,2,3,1,1,1]
  [0,4,-1,1,-1,2] ]

因此具有递减值的第三和第五列将保持不变,而其他列被替换为差异列,结果是:

[ [0,2,4,1,4,1]
  [0,4,3,1,2,2] ]

我尝试过这样的事情:

tempX = np.diff(X, axis = 0).transpose()
return np.where(tempX >= 0, tempX, X[1:].transpose())

np.where 中的条件是按元素执行的,而不是针对每一列(或每一行)。

如何更改条件以使其正常工作?有没有更有效的方法来实现这一点?

【问题讨论】:

  • 您能否使用更大的数组作为样本并提供更多种类的数字?
  • 很难理解您的示例中是否存在拼写错误。 ;) 我猜应该是“会改成[ [0, 2, 1] [0, 4, 3] ]”吧?
  • 我改了例子,希望现在更清楚?

标签: python arrays numpy


【解决方案1】:

你可以这样试试:

b = a[1:] - a[:-1]
decrease = numpy.where(numpy.min(b, axis=0)<0)
b[:,decrease] = a[1:, decrease]

你也可以在一个表达式中做到这一点:

numpy.where(numpy.min(a[1:]-a[:-1],axis=0)>=0, a[1:]-a[:-1], a[1:])

【讨论】:

    【解决方案2】:

    你可以使用boolean-indexing -

    # Get the differentiation along first axis
    diffs = np.diff(a,axis=0)
    
    # Mask of invalid ones
    mask = (diffs<0).any(0)
    
    # Use the mask to set the invalid ones to the original elements
    diffs[:,mask] = a[1:,mask]
    

    示例运行 -

    In [141]: a
    Out[141]: 
    array([[1, 1, 1, 2, 3, 4],
           [1, 3, 4, 3, 4, 5],
           [1, 7, 3, 4, 2, 7]])
    
    In [142]: diffs = np.diff(a,axis=0)
         ...: mask = (diffs<0).any(0)
         ...: diffs[:,mask] = a[1:,mask]
         ...: 
    
    In [143]: diffs
    Out[143]: 
    array([[0, 2, 4, 1, 4, 1],
           [0, 4, 3, 1, 2, 2]])
    

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 2020-11-07
      • 2020-04-17
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      相关资源
      最近更新 更多