Python numpy数组元素没有';当给它赋值时,不要改变它的值

Python numpy数组元素没有';当给它赋值时,不要改变它的值,python,arrays,numpy,Python,Arrays,Numpy,我在为这件事发愁。我试图更改numpy数组的元素,但没有效果: import numpy as np c = np.empty((1), dtype='i4, S, S, S, S, S, S, S, S, S') print(c) c[0][1]="hello" c[0][2]='hello' c[0][3]=b'hello' print(c) 输出: [(0, b'', b'', b'', b'', b'', b'', b'', b'', b'')] [(0, b'', b'', b'',

我在为这件事发愁。我试图更改numpy数组的元素,但没有效果:

import numpy as np
c = np.empty((1), dtype='i4, S, S, S, S, S, S, S, S, S')
print(c)
c[0][1]="hello"
c[0][2]='hello'
c[0][3]=b'hello'
print(c)
输出:

[(0, b'', b'', b'', b'', b'', b'', b'', b'', b'')]
[(0, b'', b'', b'', b'', b'', b'', b'', b'', b'')]

字符串的长度以numpy为单位固定。不适合的内容将被丢弃:

np.array('hello', dtype='S4')
# array(b'hell', dtype='|S4')
dtype('S')
似乎等同于
dtype('S0')

因此,分配给它会使字符串在位置
0
处被截断

如果您提前知道预期的最大长度:

c = np.empty((1,), dtype=', '.join(['i4'] + 9*['S5']))
for i in range(1, 10):
    c[0][i] = 'hello'

c
# array([ (-1710610776, b'hello', b'hello', b'hello', b'hello', b'hello', b'hello', b'hello', b'hello', b'hello')],
#   dtype=[('f0', '<i4'), ('f1', 'S5'), ('f2', 'S5'), ('f3', 'S5'), ('f4', 'S5'), ('f5', 'S5'), ('f6', 'S5'), ('f7', 'S5'), ('f8', 'S5'), ('f9', 'S5')])
c=np.empty((1,),dtype=','.join(['i4']+9*['S5']))
对于范围(1,10)内的i:
c[0][i]=“你好”
C
#数组([-1710610776,b'hello',b'hello',b'hello',b'hello',b'hello',b'hello',b'hello',b'hello'),

#dtype=[('f0','您使用的字符串长度为0。您必须使字段足够大以容纳文本:

import numpy as np
c = np.empty((1), dtype='i4, S5, S5, S5, S5, S5, S5, S5, S5, S5')
print(c)
c[0][1]="hello"
c[0][2]='hello'
c[0][3]=b'hello'
print(c)

你在用那个
dype做什么?
?数组每行应该包含10个元组。在本例中为1行。我从一些numpy页面中选择了这个示例。-
x=np.zero(3,dtype='3int8,float32,(2,3)float64')
c = np.empty((1,), dtype=', '.join(['i4'] + 9*['O']))
for i in range(1, 10):
    c[0][i] = 'hello world'[:i]

c
# array([ (0, 'h', 'he', 'hel', 'hell', 'hello', 'hello ', 'hello w', 'hello wo', 'hello wor')],
#   dtype=[('f0', '<i4'), ('f1', 'O'), ('f2', 'O'), ('f3', 'O'), ('f4', 'O'), ('f5', 'O'), ('f6', 'O'), ('f7', 'O'), ('f8', 'O'), ('f9', 'O')])
lot = [(5,) + tuple('hello world 2 3 4 5 6 7 8 9'.split()), (8,) + tuple('0 1 2 3 short loooooooong 6 7 8 9'.split())]
lot
# [(5, 'hello', 'world', '2', '3', '4', '5', '6', '7', '8', '9'), (8, '0', '1', '2', '3', 'short', 'loooooooong', '6', '7', '8', '9')]
c = np.rec.fromrecords(lot)
c
# rec.array([(5, 'hello', 'world', '2', '3', '4', '5', '6', '7', '8', '9'),
#       (8, '0', '1', '2', '3', 'short', 'loooooooong', '6', '7', '8', '9')], 
#      dtype=[('f0', '<i8'), ('f1', '<U5'), ('f2', '<U5'), ('f3', '<U1'), ('f4', '<U1'), ('f5', '<U5'), ('f6', '<U11'), ('f7', '<U1'), ('f8', '<U1'), ('f9', '<U1'), ('f10', '<U1')])
import numpy as np
c = np.empty((1), dtype='i4, S5, S5, S5, S5, S5, S5, S5, S5, S5')
print(c)
c[0][1]="hello"
c[0][2]='hello'
c[0][3]=b'hello'
print(c)