将标量与Numpy数组进行比较[duplicate]

时间:2021-11-14 08:08:52

This question already has an answer here:

这个问题已经有了答案:

What I am trying to do is make a table based on a piece-wise function in Python. For example, say I wrote this code:

我要做的是基于Python中的分段函数创建一个表。例如,假设我写了这个代码:

import numpy as np
from astropy.table import Table, Column
from astropy.io import ascii
x = np.array([1, 2, 3, 4, 5])
y = x * 2
data = Table([x, y], names = ['x', 'y'])
ascii.write(data, "xytable.dat")
xytable = ascii.read("xytable.dat")
print xytable

This works as expected, it prints a table that has x values 1 through 5 and y values 2, 4, 6, 8, 10.

它按预期工作,它打印一个表,其中x值为1到5,y值为2 4 6 8 10。

But, what if I instead want y to be x * 2 only if x is 3 or less, and y to be x + 2 otherwise?

但是,如果我想让y = x * 2只当x小于等于3,而y = x + 2呢?

If I add:

如果我添加:

if x > 3: 
    y = x + 2

it says:

它说:

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

具有多个元素的数组的真值是不明确的。使用a.any()或所有()

How do I code my table so that it works as a piece-wise function? How do I compare scalars to Numpy arrays?

如何将表编码为分段函数?如何比较标量和Numpy数组?

2 个解决方案

#1


3  

You can possibly use numpy.where():

可以使用numpi .where():

In [196]: y = np.where(x > 3, x + 2, y)

In [197]: y
Out[197]: array([2, 4, 6, 6, 7])

The code above gets the job done in a fully vectorized manner. This approach is generally more efficient (and arguably more elegant) than using list comprehensions and type conversions.

上面的代码以完全向量化的方式完成工作。与使用列表理解和类型转换相比,这种方法通常更有效(也可以说更优雅)。

#2


1  

Start off not using numpy (or maybe you can, I don't know numpy) and just do in using regular python lists.

一开始不要使用numpy(或者你可以,我不知道numpy),而是使用常规的python列表。

x = [ 1, 2, 3, 4, 5 ]
y = [ i * 2 if i < 3 else i + 2 for i in x ]
print y

Outputs:

输出:

[2, 4, 5, 6, 7]

Then you can make it a numpy array:

然后你可以把它变成一个numpy数组:

x = np.array(x)
y = np.array(y)

#1


3  

You can possibly use numpy.where():

可以使用numpi .where():

In [196]: y = np.where(x > 3, x + 2, y)

In [197]: y
Out[197]: array([2, 4, 6, 6, 7])

The code above gets the job done in a fully vectorized manner. This approach is generally more efficient (and arguably more elegant) than using list comprehensions and type conversions.

上面的代码以完全向量化的方式完成工作。与使用列表理解和类型转换相比,这种方法通常更有效(也可以说更优雅)。

#2


1  

Start off not using numpy (or maybe you can, I don't know numpy) and just do in using regular python lists.

一开始不要使用numpy(或者你可以,我不知道numpy),而是使用常规的python列表。

x = [ 1, 2, 3, 4, 5 ]
y = [ i * 2 if i < 3 else i + 2 for i in x ]
print y

Outputs:

输出:

[2, 4, 5, 6, 7]

Then you can make it a numpy array:

然后你可以把它变成一个numpy数组:

x = np.array(x)
y = np.array(y)