Python数组赋值

时间:2014-05-23 13:54:52

标签: python arrays numpy variable-assignment

我在Python中为变量赋值时遇到了问题

import numpy
a = numpy.empty((3,3,))
a[:] = numpy.NaN
a
b=a
b[numpy.isnan(b)]=1

直到倒数第二行a和b等于NaN数组:

>>> a
array([[ nan,  nan,  nan],
       [ nan,  nan,  nan],
       [ nan,  nan,  nan]])
>>> b
array([[ nan,  nan,  nan],
       [ nan,  nan,  nan],
       [ nan,  nan,  nan]])

但是当执行最后一个语句时(即b [numpy.isnan(b)] = 1)a和b都成为1的数组

>>> a
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])
>>> b
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])

如何将数组b设置为1,将数组a设置为NaN。请注意,我需要维护b = a语句

4 个答案:

答案 0 :(得分:2)

您可以使用

 b=numpy.copy(a)

然后b[numpy.isnan(b)]=1

In [45]: a[:] = numpy.NaN

In [46]: b=numpy.copy(a)

In [47]: b[numpy.isnan(b)]=1

In [48]: a
Out[48]: 
array([[ nan,  nan,  nan],
       [ nan,  nan,  nan],
       [ nan,  nan,  nan]])

In [49]: b
Out[49]: 
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])

使用b =a[:]将不适用于您的示例,如果您更改任何一个数组,值将会更改。

In [102]: import numpy

In [103]: a = numpy.empty((3,3,))

In [104]: a[:] = numpy.NaN

In [105]: a
Out[105]: 
array([[ nan,  nan,  nan],
       [ nan,  nan,  nan],
       [ nan,  nan,  nan]])

In [106]: b=a[:]

In [107]: b
Out[107]: 
array([[ nan,  nan,  nan],
       [ nan,  nan,  nan],
       [ nan,  nan,  nan]])

In [108]: b[numpy.isnan(b)]=1

In [109]: a
Out[109]: 
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])

In [110]: b
Out[110]: 
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])
In [111]: a[:] = numpy.NaN

In [112]: a
Out[112]: 
array([[ nan,  nan,  nan],
       [ nan,  nan,  nan],
       [ nan,  nan,  nan]])

In [113]: b
Out[113]: 
array([[ nan,  nan,  nan],
       [ nan,  nan,  nan],
       [ nan,  nan,  nan]])

答案 1 :(得分:1)

你遇到的问题是python中的对象是通过引用传递的,这意味着当你你已经复制它时,它实际上只是一个阴影的原始内容和任何更改都会反映出来。

你需要使用numpy.copy()克隆数组的pythonic方法是切片:

b = a[:]

但这并不适用于numpy.ndarray因为它们有不同的行为。切片不会创建副本,因此您必须使用:

b = numpy.copy(a)

请参阅:

Bug or feature: cloning a numpy array w/ slicing

证明:

>>> def setOnes(nparr):
...     nparr[:] = 1
...
>>> a = numpy.empty((3,3,))
>>> a[:] = numpy.NaN
>>> b = a[:]
>>> a
array([[ nan,  nan,  nan],
       [ nan,  nan,  nan],
       [ nan,  nan,  nan]])
>>> setOnes(a)
>>> a
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])
>>> b
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])
>>> a[:] = numpy.NaN
>>> a
array([[ nan,  nan,  nan],
       [ nan,  nan,  nan],
       [ nan,  nan,  nan]])
>>> b = numpy.copy(a)
>>> b
array([[ nan,  nan,  nan],
       [ nan,  nan,  nan],
       [ nan,  nan,  nan]])
>>> setOnes(b)
>>> b
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]])
>>> a
array([[ nan,  nan,  nan],
       [ nan,  nan,  nan],
       [ nan,  nan,  nan]])

答案 2 :(得分:0)

查看复制模块。我认为深度复印是你想要的。

或者,您可以写b = a [:]。

而不是b = a

答案 3 :(得分:0)

b = aa引用复制到b而不是a引用的对象内容。

尝试:

b = numpy.array(a)