出于某种原因,我很难用空格初始化 numpy.chararray
。
这有效:
char_array1 = np.chararray((3, 3))
char_array1[:] = 'a'
char_array1
输出:
chararray([['a', 'a', 'a'],
['a', 'a', 'a'],
['a', 'a', 'a']],
dtype='|S1')
这不会:
char_array2 = np.chararray((3, 3))
char_array2[:] = ' '
char_array2
输出:
chararray([['', '', ''],
['', '', ''],
['', '', '']],
dtype='|S1')
这是什么原因造成的?我看不到删除元素或其他东西的选项。
最佳答案
事实上,字符数组确实会删除空格:
Versus a regular NumPy array of type str or unicode, this class adds the following functionality:
values automatically have whitespace removed from the end when indexed comparison operators automatically remove whitespace from the end when comparing values vectorized string operations are provided as methods (e.g. endswith) and infix operators (e.g. "+", "*", "%")
所以答案是使用 str 或 unicode 类型的常规数组:
char_array3 = np.empty((3, 3), dtype='str')
char_array3[:] = ' '
char_array3
输出:
array([[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']],
dtype='|S1')
关于python - 如何用空格填充Python numpy chararray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43839709/