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)
必须有一个简单的解决方案来做到这一点,而不使用痛苦的循环,但我找不到它.
在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)
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)
归档时间: |
|
查看次数: |
75 次 |
最近记录: |