【问题标题】:find position of column string in another column using Pandas使用 Pandas 在另一列中查找列字符串的位置
【发布时间】:2019-03-16 20:01:39
【问题描述】:

我有一个包含 2 列的数据框

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

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

解决方案必须是:

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

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

【问题讨论】:

    标签: python string pandas


    【解决方案1】:

    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
    

    【讨论】:

    • 谢谢,这似乎是我要找的。你知道是否有 Pandas 等价物吗?
    • 粗略的等价物是df.col2.str.find('cat'),但它无法进行成对查找。
    【解决方案2】:

    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
    

    【讨论】:

    • 我的 DataFrame 有 100 万行,我的字符串可以是 50000 字符长度。我真的不想尝试这个。 Pandas/Numpy 函数被用来加速这种繁重的事情
    • 确实,通常pandasnumpy 函数是为了加快速度,但在字符串的情况下,提供的方法通常无法提供速度提升。在你的情况下,我没有用大字符串的大数据帧来计时,但它可能没有你预期的那么慢。
    猜你喜欢
    • 2021-05-04
    • 2018-12-02
    • 1970-01-01
    • 2018-05-03
    • 2017-10-08
    • 1970-01-01
    • 2022-01-03
    • 2018-04-21
    相关资源
    最近更新 更多