使用Pandas在另一列中查找列字符串的位置

Moh*_*ANI 4 python string pandas

我有一个包含2列的Dataframe

   col1     col2
1  cat      the cat
2  dog      a nice dog
3  horse    horse is here
Run Code Online (Sandbox Code Playgroud)

我需要在col2中找到每个col1字符串的位置.

解决方案必须是:

   col1     col2          col3
1  cat      the cat        4
2  dog      a nice dog     7
3  horse    horse is here  0
Run Code Online (Sandbox Code Playgroud)

必须有一个简单的解决方案来做到这一点,而不使用痛苦的循环,但我找不到它.

sac*_*cuL 5

pandas使用字符串时,循环或列表理解通常会比内置字符串方法更快。就您而言,它可能会很短:

df['col3'] = [i2.index(i1) for i1,i2 in zip(df.col1,df.col2)]

>>> df
    col1           col2  col3
1    cat        the cat     4
2    dog     a nice dog     7
3  horse  horse is here     0
Run Code Online (Sandbox Code Playgroud)


piR*_*red 5

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
Run Code Online (Sandbox Code Playgroud)