0

I have a data frame like this called: Numbers

Words
One
Two
Three
Four
Five

And a second data frame like this called: Phrases

Words
One Fish
Two Fish
Red Fish
Blue Fish
Four Men
Five Men
Wise One
One Day

What I was hoping to do was iterate through each word in the first list (i.e. One, Two, Three, Four, Five) and find those words in the second data frame where the FIRST WORD MATCHES

So a search for 'One' in the first data frame would turn up 'One Fish' and 'One Day' but NOT 'Wise One' -- a search for 'Two' would turn up 'Two Fish'.

I've tried something like this but not only does it NOT work, it only searches for whole words

for wordz in exact: #exact is the variable that contains the "Numbers" DF
    for freqz in freq: #freq contains "Phrases" DF
        wordz = exact[exact['Words'].isin([freq[freq['Words']]])]
        print(wordz)

but I get an error: KeyError: "['One Fish','Two Fish'...'Wise One'] not in index"

1 Answer 1

1

You need to extract prefixes and then do a left join. I am calling the first frame left and the second frame right:

>>> right['Prefix'] = right['Words'].str.extract(r'([^ ]*)')
>>> right
       Words Prefix
0   One Fish    One
1   Two Fish    Two
2   Red Fish    Red
3  Blue Fish   Blue
4   Four Men   Four
5   Five Men   Five
6   Wise One   Wise
7    One Day    One
>>> left.join(right.set_index('Prefix'), on='Words', rsuffix='.1')
   Words   Words.1
0    One  One Fish
0    One   One Day
1    Two  Two Fish
2  Three       NaN
3   Four  Four Men
4   Five  Five Men

or:

>>> pd.merge(left, right, how='left', left_on='Words', right_on='Prefix', suffixes=('', '.1'))
   Words   Words.1 Prefix
0    One  One Fish    One
1    One   One Day    One
2    Two  Two Fish    Two
3  Three       NaN    NaN
4   Four  Four Men   Four
5   Five  Five Men   Five
2
  • Hey Behzad, I actually thought about merging the two data frame on single words. Unfortunately, I can't reindex because the objects are not uniquely valued in my original data frame, i.e. there is more than one phrase in the 2nd dataframe that starts with 'One'. Sep 16, 2014 at 22:08
  • @user3682157 if you have master branch of pandas left join on index with multiple matches is fixed through this pull request. if you do not have master branch specify how='outer' in the last line, and then drop rows which are null in first column, or use pd.merge. Sep 16, 2014 at 22:12

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.