【问题标题】:Numpy array assignmentNumpy 数组赋值
【发布时间】:2012-03-15 16:01:42
【问题描述】:

我编写了一个非常简单的 python numpy 代码。它有一个奇怪的行为......

from numpy import *
# generate 2 array with 15 random int between 1 and 50
pile = random.randint(1, 50, 15)
pile2 = copy(pile)

print("*** pile2",type(pile2),pile2)
print("tab with fixed values ")
tmp2=array([155,156,157,158,159])
print("tmp2",type(tmp2),tmp2)
pile2[:5]=tmp2
print("pile2",type(pile2),pile2)

print("*** pile",type(pile),pile)
print("flip a part of pile and put in an array")
tmp=pile[4::-1]
print("tmp",type(tmp),tmp)
pile[:5]=tmp
print("pile",type(pile),pile)

当我运行这个脚本时,它会返回:

*** pile2 <class 'numpy.ndarray'> [20 23 29 31  8 29  2 44 46 17 11 47 29 43 10]
tab with fixed values 
tmp2 <class 'numpy.ndarray'> [155 156 157 158 159]
pile2 <class 'numpy.ndarray'> [155 156 157 158 159  29   2  44  46  17  11  47  29  43  10]

好的! pile2 变成类似“tmp2[] 和 pile2[6::]”的东西,但是对于第二个......

*** pile <class 'numpy.ndarray'> [20 23 29 31  8 29  2 44 46 17 11 47 29 43 10]
flip a part of pile and put in an array
tmp <class 'numpy.ndarray'> [ 8 31 29 23 20]
pile <class 'numpy.ndarray'> [ 8 31 29 31  8 29  2 44 46 17 11 47 29 43 10]

tmp [ 8 31 29 23 20]

桩 [8 31 29 31 8 29 2 44 46 17 11 47 29 43 10]

哦!赋值有问题!发生了什么?

【问题讨论】:

  • 我无法复制这种行为。您的代码中的其他地方可能存在错误。顺便说一句,尽量避免使用from [module] import *,因为它可能会导致与命名空间相关的问题。

标签: python arrays numpy


【解决方案1】:

我可以使用 numpy 1.3.0 确认该行为。我想这确实是一个老错误。还有这个:

pile[:5]=tmp.copy() 

解决问题。

【讨论】:

    【解决方案2】:

    因为tmp是一个pile的视图,当你用它来设置pile的内容时会出现问题。我正在使用 NumPy 1.6.1,并且无法复制它,所以这可能在最新版本中已修复。如果您使用的是旧版本,您可以尝试:

    tmp=pile[4::-1]
    pile[:5]=tmp.copy()
    

    【讨论】:

      猜你喜欢
      • 2011-03-04
      • 2013-02-08
      • 1970-01-01
      • 2020-07-31
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      • 2014-11-04
      相关资源
      最近更新 更多