简体   繁体   中英

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?

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]

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]

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM