我可以清理无循环的numpy数组吗? [英] Can I cleanse a numpy array without a loop?

查看:69
本文介绍了我可以清理无循环的numpy数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许没什么大不了的,但是遵循这一点让我很伤心:

Perhaps not such a big deal, but it breaks my heart to follow this:

deltas = data[1:] - data[:-1]

与此:

for i in range(len(deltas)):
        if deltas[i] < 0: deltas[i] = 0
        if deltas[i] > 100: deltas[i] = 0

对于此特定示例...是否有更好的方法进行清洁?

For this particular example...is there a better way to do the cleansing part?

问题第二部分:如果清理规则比本示例更复杂或更不复杂,该怎么办?例如,我们可能只想将所有负数更改为零.或者,我们可能正在做更复杂的映射.

Question part two: What if the cleansing rules are more complicated, or less complicated than this example. For example, we might just want to change all negative numbers to zero. Or, we might be doing a more complicated mapping.

推荐答案

import numpy as np
deltas=np.diff(data)
deltas[deltas<0]=0
deltas[deltas>100]=0

也可以,并且更快一点

deltas[(deltas<0) | (deltas>100)]=0

这篇关于我可以清理无循环的numpy数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆