Replace character in numpy ndarray (Python)

痞子三分冷 提交于 2021-01-29 02:48:21

问题


I have a numpy ndarray with 6 elements:

['\tblah blah' '"""123' 'blah' '"""' '\t456' '78\t9']

I am trying to replace all tab characters \t with 4 spaces each so that the numpy array would now be:

[' blah blah' '"""123' 'blah' '"""' ' 456' '78 9']

I have considered re.sub but cannot figure out how to implement it when it comes down to an numpy ndarray. Any suggestions/help please?


回答1:


You could use NumPy's core.defchararray that deals with string related operations and for this case use replace method, like so -

np.core.defchararray.replace(arr,'\t', '    ')

Sample run -

In [44]: arr
Out[44]: 
array(['\tblah blah', '"""123', 'blah', '"""', '\t456', '78\t9'], 
      dtype='|S10')

In [45]: np.core.defchararray.replace(arr,'\t', '    ')
Out[45]: 
array(['    blah blah', '"""123', 'blah', '"""', '    456', '78    9'], 
      dtype='|S13')


来源:https://stackoverflow.com/questions/40957764/replace-character-in-numpy-ndarray-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!