Python3 Numpy np.where错误 [英] Python3 Numpy np.where Error
问题描述
我有2个这样的列表
x = [None,[1, 15, 175, 20],
[150, 175, 18, 20],
[150, 175, 18],
[192, 150, 177],...]
y = [None,[12, 43, 55, 231],
[243, 334, 44, 12],
[656, 145, 138],
[12, 150, 177],
[150, 177, 188],...]
现在,我想擦除小于30的x值和与擦除的x值相对应的y值. (例如,x [1]和y [1]中的(x,y)=(1,12))
Now I want to erase the x values lower than 30 and y values that correspond with the erased x values. (For example, (x,y) = (1,12) in x[1] and y[1])
为此,我尝试在Numpy中使用np.where.
In order to do that, I tried to use np.where in Numpy.
我使用np.array将x和y列表转换为数组,并将其用于x
I converted the x and y lists into arrays by using np.array and got this for x
array([None, list([11]), list([12, 11]), ..., list([12, 13]),list([13, 13]), list([13, 15])], dtype=object)
然后我使用np.where(a< 30)并收到此错误
Then I used np.where(a<30) and got this error
TypeError: '>' not supported between instances of 'NoneType' and 'int'
我认为第一个列表中的None值是问题,所以我实现了
I thought the None values in the first lists were the problem so I implemented
np.where(a[1:]>30)
然后我得到了 TypeError:"list"和"int"的实例之间不支持>"
Then I got TypeError: '>' not supported between instances of 'list' and 'int'
我是一个初学者,想知道是什么导致了此错误.
I'm a beginner and want to know what caused this errors.
推荐答案
使用列表理解:
In [161]: x = [None,[1, 15, 175, 20],
...: [150, 175, 18, 20],
...: [150, 175, 18],
...: [192, 150, 177]]
...:
我们要从x
(和y
?)中删除的项目的索引.我使用x[1:]
跳过了None
,这需要额外的测试:
Indices of items that we want to remove from x
(and y
?). I use x[1:]
to skip the None
which needs an extra test:
In [163]: [(i,j) for i,v1 in enumerate(x[1:]) for j,v2 in enumerate(v1) if v2<30]
Out[163]: [(0, 0), (0, 1), (0, 3), (1, 2), (1, 3), (2, 2)]
x
中的值为>=30
:
In [164]: [[v2 for v2 in v1 if v2>=30] for v1 in x[1:]]
Out[164]: [[175], [150, 175], [150, 175], [192, 150, 177]]
我们可以使用Out[163]
值从y
中删除项目.另外,我们可以一起迭代x
和y
(zip(x,y)
等).
We could use the Out[163]
values to remove items from y
. Alternatively we could iterate through x
and y
together (zip(x,y)
, etc).
如果列表理解太混乱,则可以将其重写为循环,也可以重新编写功能.
If the list comprehensions get too messy they can be rewritten as loops, and possibly functions.
对于像这样的不规则嵌套列表结构,我认为使用numpy
没有任何意义.对象dtype数组基本上是列表(但没有有用的列表方法).
With an irregular nested list structure like this I don't see any point to using numpy
. Object dtype arrays are basically lists (but without useful list methods).
这篇关于Python3 Numpy np.where错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!