1

I have a numpy 2D array like so:

[['a', '(junk, b)', '(junk, c)'],
 ['d', '(junk, e)', '(junk, f)'],
 ['g', '(junk, h)', '(junk, i)']]

As you can see some of the values have a parenthesis around them, I'd like to remove these extra values such that my new array is:

[['a', 'b', 'c'],
 ['d', 'e', 'f'],
 ['g', 'h', 'i']]

I have a regex to get the match group of the data I want to capture but is there a clean way within numpy to apply a regex to certain values at certain positions and return my new array with the unwanted values replaced?

1
  • For all practical purposes you have a nested list of lists. Making it an object array, especially for operations like this, doesn't add much. Commented Oct 15, 2015 at 21:34

1 Answer 1

2

You can use a nested list comprehension to strip the items with str.strip() method :

>>> np.array([[x.strip('()') for x in i] for i in l])
array([['a', 'b', 'c'],
       ['d', 'e', 'f'],
       ['g', 'h', 'i']], 
      dtype='|S1')

Based on your edit if you have extra words in your array you can use regex to match the single characters :

>>> l=[['a', '(junk, b)', '(junk, c)'],
...  ['d', '(junk, e)', '(junk, f)'],
...  ['g', '(junk, h)', '(junk, i)']]
>>> 
>>> np.array([[re.search(r'\b[a-z]\b',x).group() for x in i] for i in l])
array([['a', 'b', 'c'],
       ['d', 'e', 'f'],
       ['g', 'h', 'i']], 
      dtype='|S1')
>>> 
Sign up to request clarification or add additional context in comments.

1 Comment

This works, however I've edited my post to be a more accurate representation of the data, instead of applying strip I need to apply a regex that captures the desired data, would it be possible to capture the data that I want and ignore the rest of the data that's already formatted properly?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.