Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find position of column string in another column using Pandas

I have a Dataframe with 2 columns

   col1     col2
1  cat      the cat
2  dog      a nice dog
3  horse    horse is here

I need to find the position of each string of col1 in col2.

Solution must be:

   col1     col2          col3
1  cat      the cat        4
2  dog      a nice dog     7
3  horse    horse is here  0

There must be a simple solution to do this without using painful loops, but i can't find it.

like image 925
Mohamed AL ANI Avatar asked Jan 27 '23 08:01

Mohamed AL ANI


1 Answers

numpy.core.defchararray.find

from numpy.core.defchararray import find

a = df.col2.values.astype(str)
b = df.col1.values.astype(str)
df.assign(col3=find(a, b))

    col1           col2  col3
1    cat        the cat     4
2    dog     a nice dog     7
3  horse  horse is here     0
like image 97
piRSquared Avatar answered Feb 07 '23 19:02

piRSquared