Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way to replace parts of strings in NumPy array

I have a NumPy string array

['HD\,315', 'HD\,318' ...]

I need to replace every 'HD\,' to 'HD ', i.e. I want to get new array like below

 ['HD 315', 'HD 318' ...]

What is the SHORTEST way to solve this task in Python? Is it possible to do this without FOR loop?

like image 632
drastega Avatar asked Jan 27 '14 16:01

drastega


2 Answers

Use python list comprehension:

L = ['HD\,315', 'HD\,318' ]
print [s.replace('HD\,' , 'HD ') for s in L]

But it uses for

Alternatively you can use map():

print map(lambda s: s.replace('HD\,' , 'HD '), L)

for python3 use list(map(lambda s: s.replace('HD\,' , 'HD '), L))

like image 110
Grijesh Chauhan Avatar answered Sep 29 '22 11:09

Grijesh Chauhan


You can use the numpy.core.defchararray.replace function, which performs the for operation using numpy instead:

import numpy.core.defchararray as np_f

data = ['HD\,315', 'HD\,318']

new_data = np_f.replace(data, 'HD\,', 'HD')
like image 42
user2750362 Avatar answered Sep 29 '22 10:09

user2750362