【问题标题】:Can NumPy take care that an array is (nonstrictly) increasing along one axis?NumPy 可以注意数组(非严格)沿一个轴增加吗?
【发布时间】:2017-11-13 15:38:54
【问题描述】:

numpy 中是否有一个函数来保证或修复一个数组,使其(非严格地)沿着一个特定的轴增加? 例如,我有以下二维数组:

X = array([[1, 2, 1, 4, 5],
           [0, 3, 1, 5, 4]])

np.foobar(X) 的输出应该返回

array([[1, 2, 2, 4, 5],
       [0, 3, 3, 5, 5]])

foobar 是否存在,还是我需要通过使用类似 np.diff 和一些智能索引来手动执行?

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    使用np.maximum.accumulate 沿该轴运行(累积)最大值,以确保严格增加标准 -

    np.maximum.accumulate(X,axis=1)
    

    示例运行 -

    In [233]: X
    Out[233]: 
    array([[1, 2, 1, 4, 5],
           [0, 3, 1, 5, 4]])
    
    In [234]: np.maximum.accumulate(X,axis=1)
    Out[234]: 
    array([[1, 2, 2, 4, 5],
           [0, 3, 3, 5, 5]])
    

    为了提高内存效率,我们可以使用其out 参数将其分配回输入以进行原位更改。

    运行时测试

    案例#1:数组作为输入

    In [254]: X = np.random.rand(1000,1000)
    
    In [255]: %timeit np.maximum.accumulate(X,axis=1)
    1000 loops, best of 3: 1.69 ms per loop
    
    # @cᴏʟᴅsᴘᴇᴇᴅ's pandas soln using df.cummax
    In [256]: %timeit pd.DataFrame(X).cummax(axis=1).values
    100 loops, best of 3: 4.81 ms per loop
    

    案例#2:数据框作为输入

    In [257]: df = pd.DataFrame(np.random.rand(1000,1000))
    
    In [258]: %timeit np.maximum.accumulate(df.values,axis=1)
    1000 loops, best of 3: 1.68 ms per loop
    
    # @cᴏʟᴅsᴘᴇᴇᴅ's pandas soln using df.cummax
    In [259]: %timeit df.cummax(axis=1)
    100 loops, best of 3: 4.68 ms per loop
    

    【讨论】:

      【解决方案2】:

      pandas 为您提供df.cummax 功能:

      import pandas as pd
      pd.DataFrame(X).cummax(axis=1).values
      
      array([[1, 2, 2, 4, 5],
             [0, 3, 3, 5, 5]])
      

      如果您的数据已经加载到数据帧中,知道手头有一个一流的函数会很有用。

      【讨论】:

      • 我喜欢 pandas 并且经常使用它,但在这种特殊情况下,我只有 numpy 数组,我不想动态创建一个新框架,只是为了这个 :-)。不过,谢谢,很高兴知道 pandas 也有这个功能!
      • @SmCaterpillar 没问题。它本身当然没有意义。如果您的数据已经在 数据框中,您会考虑这一点。 :)
      猜你喜欢
      • 2018-09-01
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      • 2021-05-29
      • 2020-08-01
      • 2011-06-29
      • 2011-01-22
      相关资源
      最近更新 更多