python - 如何用空格填充Python numpy chararray?

标签 python arrays numpy char

出于某种原因,我很难用空格初始化 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/

相关文章:

python - 为什么操作完成后可以访问列表理解变量?

python - 我如何从硬编码的url中获取scrapy中解析的html

java - 使用 getParameterValues 和数组

c - 有条件地输入数组

python - Pandas 使用跨多个列的字典值相乘

python - 有什么办法可以让这台发电机干涸吗?

python - Web 应用程序中的动态子域处理(Flask)

c++ - 打开大括号导致语法错误

python - 独立移动 numpy 数组的行

Python pandas - Dataframe 使用 pd.groupby().agg() 获得第二高值