替换 numpy ndarray 中的字符(Python) [英] Replace character in numpy ndarray (Python)

查看:158
本文介绍了替换 numpy ndarray 中的字符(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 6 个元素的 numpy ndarray:

I have a numpy ndarray with 6 elements:

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

我正在尝试将所有制表符 \t 替换为 4 个空格,以便 numpy 数组现在是:

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

我已经考虑过 re.sub,但是当它归结为一个 numpy ndarray 时,我无法弄清楚如何实现它.请问有什么建议/帮助吗?

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?

推荐答案

你可以使用 NumPy 的 core.defchararray 处理与字符串相关的操作,在这种情况下使用 replace 方法,像这样 -

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', '    ')

样品运行 -

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')

这篇关于替换 numpy ndarray 中的字符(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆