NumPy可以注意一个阵列(非严格地)沿着一个轴增加吗?

时间:2017-11-13 15:38:55

标签: python arrays numpy

numpy中是否有一个函数可以保证或者更确切地修复一个数组,使其沿着一个特定的轴(非严格地)增加? 例如,我有以下2D数组:

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和某些智能索引等手动执行此操作?

2 个答案:

答案 0 :(得分:5)

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

var db0010016 = _idb0010016Rep.GetAll().Where(e => e.ExecutionTime.TimeOfDay.ToString() == viewmodel.ExecutionTime.ToString()).FirstOrDefault()

示例运行 -

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]]) 参数将其分配回输入以进行原位更改。

运行时测试

案例#1:数组作为输入

out

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

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

答案 1 :(得分: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]])

如果您的数据已经加载到数据框中,那么知道手头有第一类函数是很有用的。