python查找数组元素中最大值,将数组的元素与标量进行比较,并在Python中获取最大值...

这篇博客介绍了如何使用numpy库在Python中比较数组元素与标量,并返回包含最大值的新数组。通过示例展示了np.maximum()函数的用法,该函数可以快速、有效地进行元素级比较且不会改变原始数组。如果希望修改原数组,可以使用np.maximum()的第三个参数实现。
摘要由CSDN通过智能技术生成

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)

and want to get

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

But I get

ValueError: 'axis' entry is out of bounds

When I run

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

I get

[1, 2, 3, 4]

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?

解决方案

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])

This doesn't mutate a:

a

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

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])

Element-wise maximum of array elements.

Equivalent to np.where(x1 > x2, x1, x2) but faster and does proper broadcasting.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值