【问题标题】:Python: Why can't I assign new value to an array in this case?Python:在这种情况下,为什么我不能为数组分配新值?
【发布时间】:2017-02-24 14:16:51
【问题描述】:
import numpy as np

data = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53']])
data[0,0] = data[0,0] + "_1"

data[0,0] 是 'Height',我想将其替换为 'Height_1'。但是上面的代码不起作用。它返回结果为:

data[0,0]

'身高'

data[0,0] 元素保持不变。而且如果我直接替换它而不引用它自己,它仍然不起作用。

data[0,0] = "Height" + "_1"

结果:

data[0,0]

'身高'

但如果我将它替换为 "Height" 以外的其他字符,它会起作用。

data[0,0] = "str" + "_1"

结果:

data[0,0]

'str_1'

我用这个案例来解释我遇到的问题。在我的工作中,我必须引用数组本身,因为我需要替换不满足某些要求的元素。有人对此有解决方案吗?谢谢。

【问题讨论】:

  • 我认为您不应该将字符串和整数混合在一起
  • @jamylak 准确地说,OP 在这里只使用字符串。
  • @juanpa.arrivillaga 我知道,我的意思是 OP 不应该将列标题包含在数据中,并且数字不应该保存为字符串
  • @jamylak 我同意,但在这种情况下最好具体一点。

标签: python arrays numpy variable-assignment


【解决方案1】:

问题是你的数组是dtype('<U6')

>>> data = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53']])
>>> data.dtype
dtype('<U6')
>>> 

会自动截断:

>>> data[0,0] = "123456789"
>>> data
array([['123456', 'Weight'],
       ['165', '48'],
       ['168', '50'],
       ['173', '53']], 
      dtype='<U6')
>>> 

在创建数组时,您始终可以将 dtype 指定为“对象”,但这会从一开始就消除了 numpy 的许多速度优势。

或者,您可以指定更长的字符串类型:

>>> data
array([['Height', 'Weight'],
       ['165', '48'],
       ['168', '50'],
       ['173', '53']], 
      dtype='<U20')
>>> data[0,0]='Height_1'
>>> data
array([['Height_1', 'Weight'],
       ['165', '48'],
       ['168', '50'],
       ['173', '53']], 
      dtype='<U20')
>>> 

但是要小心,如果你设置的限制太长你会浪费内存:

>>> data = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53'], ['42','88']], dtype='U20')
>>> data.nbytes
800
>>> data = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53'], ['42','88']], dtype='U6')
>>> data.nbytes
240

如果您只需要有限数量的字符,请考虑使用字节串(内存需求的 1/4):

>>> data = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53'], ['42','88']], dtype='S20')
>>> data.nbytes
200
>>> 

【讨论】:

  • 或指定更长的字符串 dtype,例如U20
【解决方案2】:

为您的数组指定一个object类型,例如:

a = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53']],dtype=object)

那么, a[0][0]+='_1' 会成功的,你会得到:

array([['Height_1', 'Weight'],
       ['165', '48'],
       ['168', '50'],
       ['173', '53']], dtype=object)

【讨论】:

    猜你喜欢
    • 2021-09-20
    • 1970-01-01
    • 2021-06-19
    • 2021-12-30
    • 2021-06-05
    • 1970-01-01
    • 2017-06-11
    • 2016-06-04
    • 1970-01-01
    相关资源
    最近更新 更多