微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个包含2列的Dataframe

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

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

解决方案必须是:

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

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

解决方法:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐