将数组的元素与标量进行比较,并在Python中获取最大值 [英] Comparing elements of an array to a scalar and getting the max in Python

查看:311
本文介绍了将数组的元素与标量进行比较,并在Python中获取最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个数组的元素与一个标量进行比较,并获得一个具有最大比较值的数组.那是我想打电话的

I want to compare the elements of an array to a scalar and get an array with the maximum of the compared values. That's I want to call

import numpy as np
np.max([1,2,3,4], 3)

并想得到

array([3,3,3,4])

但是我明白了

ValueError: 'axis' entry is out of bounds

我跑步时

np.max([[1,2,3,4], 3])

我知道

[1, 2, 3, 4]

这是列表中两个元素之一,不是我要查找的结果.是否有一个Numpy解决方案能够像其他内置函数一样快速?

which is one of the two elements in the list that is not the result I seek for. Is there a Numpy solution for that which is fast as the other built-in functions?

推荐答案

这已经内置在numpy中,其功能为

This is already built into numpy with the function np.maximum:

a = np.arange(1,5)
n = 3

np.maximum(a, n)
#array([3, 3, 3, 4])

这不会变异a:

a
#array([1, 2, 3, 4])

如果您想像@jamylak的回答中那样改变原始数组,可以将a作为输出:

If you want to mutate the original array as in @jamylak's answer, you can give a as the output:

np.maximum(a, n, a)
#array([3, 3, 3, 4])

a
#array([3, 3, 3, 4])

文档:

maximum(x1, x2[, out])

逐个数组元素的最大值.
等同于np.where(x1 > x2, x1, x2),但速度更快,并且可以正常播放.

Element-wise maximum of array elements.
Equivalent to np.where(x1 > x2, x1, x2) but faster and does proper broadcasting.

这篇关于将数组的元素与标量进行比较,并在Python中获取最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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