mama
mama

Reputation: 13

How to find part of a string in a python array

I have an array with a column of numbers and a column of strings. I need to find the indices that contain a certain part of the string. Example:

array([['4', 'red crayon'],
       ['2', 'purple people eater'],
       ['6', 'red hammer'],
       ['12', 'green screwdriver']])

I am in Intro Programming so my instructors told me to use if 'stringpart' in array[index] to get a boolean array to use in our problem solving. What I think should happen:

input:
'red' in array[:,1]
output:
(true,false,true,false)

What actually happens is I get all false. I tested the code outside of functions, and applied it to an array with only the strings and it still gives me false. But I tried it with an one of the full strings 'red crayon' and it said true. This partial string code works for the instructors and other students. Why isn't it working for me?

Upvotes: 0

Views: 122

Answers (3)

Paul Panzer
Paul Panzer

Reputation: 53029

For a vectorized solution you can use the np.char module:

a = np.array([['4', 'red crayon'],
              ['2', 'purple people eater'],
              ['6', 'red hammer'],
              ['12', 'green screwdriver']])
np.char.find(a[:, 1], 'red') > -1
# array([ True, False,  True, False], dtype=bool)

Upvotes: 0

Aaditya Ura
Aaditya Ura

Reputation: 12669

You can do without for loop:

import numpy as np
wow=np.array([['4', 'red crayon'],
       ['2', 'purple people eater'],
       ['6', 'red hammer'],
       ['12', 'green screwdriver']])

your_word='red'
print(list(map(lambda x:True if your_word in x[1].split() else False ,wow)))

output:

[True, False, True, False]

Upvotes: 0

Reblochon Masque
Reblochon Masque

Reputation: 36662

You need to check is the substring is present in any of the elements of the array:

a = [['4', 'red crayon'],
     ['2', 'purple people eater'],
     ['6', 'red hammer'],
     ['12', 'green screwdriver']]

[True if any(['red' in elt for elt in sub]) else False for sub in a]

output:

[True, False, True, False]

Upvotes: 2

Related Questions