Python 如何将 numpy 数组乘以标量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17729297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:01:06  来源:igfitidea点击:

How to multiply a numpy array by a scalar

pythonarraysnumpyscalar

提问by user2596490

I have a numpy array and I'm trying to multiply it by a scalar but it keeps throwing an error:

我有一个 numpy 数组,我试图将它乘以一个标量,但它不断抛出错误:

TypeError: unsupported operand type(s) for *: 'numpy.ndarray' and 'int'

My code is:

我的代码是:

Flux140 = ['0.958900', 'null', '0.534400']
n = Flux140*3

回答by user2357112 supports Monica

That's an array of strings. You want an array of numbers. Parse the input with floator something before making the array. (What to do about those 'null's depends on your application.)

那是一个字符串数组。你想要一个数字数组。float在制作数组之前用或其他东西解析输入。(如何处理这些'null'取决于您的应用程序。)

回答by askewchan

The problem is that your array's dtypeis a string, and numpy doesn't know how you want to multiply a string by an integer. If it were a list, you'd be repeating the list three times, but an array instead gives you an error.

问题是你的数组dtype是一个字符串,而 numpy 不知道你想如何将一个字符串乘以一个整数。如果它是一个列表,您将重复该列表 3 次,但数组反而会给您一个错误。

Try converting your array's dtypefrom string to float using the astypemethod. In your case, you'll have trouble with your 'null'values, so you must first convert 'null'to something else:

尝试dtype使用该astype方法将数组从字符串转换为浮点数。在您的情况下,您的'null'值会遇到问题,因此您必须首先转换'null'为其他值:

Flux140[Flux140 == 'null'] = '-1'

Then you can make the type float:

然后你可以使类型浮动:

Flux140 = Flux140.astype(float)

If you want your 'null'to be something else, you can change that first:

如果你想让你'null'成为别的东西,你可以先改变它:

Flux140[Flux140 == -1] = np.nan

Now you can multiply:

现在你可以乘法:

tripled = Flux140 * 3