Python:为什么我无法在这种情况下为数组分配新值?

3
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]

'高度'

但是如果我将其替换为“高度”以外的一些字符,它就可以正常工作。

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

结果:

data[0,0]

'str_1'

我拿这个案例来说明我遇到的问题。在我的工作中,我需要引用数组本身,因为我需要替换那些不符合某些要求的元素。有没有人有解决方案?谢谢。


我认为你不应该混合使用字符串和整数。 - jamylak
更准确地说,OP在这里只使用字符串。 - juanpa.arrivillaga
@juanpa.arrivillaga 我知道,我的意思是 OP 不应该将列标题包含在数据中,数字也不应该保存为字符串。 - jamylak
@jamylak 我同意,但在这种情况下可能更好的是具体说明。 - juanpa.arrivillaga
2个回答

4

问题出在您的数组的 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指定为'object',但这会减少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
>>> 

或者指定更长的字符串类型,例如U20。 - hpaulj

3

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

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接