用自定义dtype替换numpy数组值



我有如下数据:

x = np.array([('joe', [1, 3, 5, 7, 9, 3, 2, 4]),
              ('sally', [7, 3, 5, 1, 4, 3, 2, 4])],
              dtype=np.dtype([('name', 'a10'), ('scores', (float, 8))]))

,我想用类似np.maximum.accumulate()的结果替换'scores'列中的值。如果我有一个numpy数组,它的值是:

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

得到如下输出:

[1 3 5 7 9 9 9 9]

,但我似乎不能得到这个工作在numpy数组具有复杂或自定义的数据类型。我认为这与创建视图和数据副本有关,但我似乎无法弄清楚。

我已经尝试了几种不同的方法:

x['scores'] = np.maximum.accumulate(x['scores'])

for i, score in enumerate(x):
   x[i]['scores'] = np.maximum.accumulate(x[i]['scores'])

,但似乎都不能替换适当的值。任何建议,我如何才能做到这一点,将是非常感谢。谢谢!

不是赋值,是np.maximum.accumulate没有返回你想的结果

>>> np.maximum.accumulate(x["scores"])
array([[ 1.,  3.,  5.,  7.,  9.,  3.,  2.,  4.],
       [ 7.,  3.,  5.,  7.,  9.,  3.,  2.,  4.]])

如果指定axis=1,则:

>>> np.maximum.accumulate(x["scores"], axis=1)
array([[ 1.,  3.,  5.,  7.,  9.,  9.,  9.,  9.],
       [ 7.,  7.,  7.,  7.,  7.,  7.,  7.,  7.]])
>>> x["scores"] = np.maximum.accumulate(x["scores"], axis=1)
>>> x
array([('joe', [1.0, 3.0, 5.0, 7.0, 9.0, 9.0, 9.0, 9.0]),
       ('sally', [7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0, 7.0])], 
      dtype=[('name', 'S10'), ('scores', '<f8', (8,))])

PS:当您使用命名列时,使用pandas比使用纯numpy要方便得多,我衷心推荐它。

最新更新