【问题标题】:Removing particular string in python pandas column删除 python pandas 列中的特定字符串
【发布时间】:2023-03-07 01:46:01
【问题描述】:

我有一个带有性别列的数据框。它包括对性别的预测。现在,性别列具有诸如 most_male、most_female 之类的值。我主要想删除。于是我试了df['gender'] = df['gender'].map(lambda x: x.lstrip('mostly_'))

但我有一个值为 'male' 的列对应于 'ale'

【问题讨论】:

    标签: python python-3.x pandas nlp


    【解决方案1】:

    pandas.DataFrame.replace

    您可以将字典传递给此方法以指定要使用的列

    df.replace({'gender': {'mostly_': ''}}, regex=True)
    

    pandas.Series.str.replace

    优点是不需要指定regex=True

    df.gender.str.replace('mostly_', '')
    

    pandas.Series.str

    投票“最可能”打破。但是,如果您知道所有条目都以 "mostly_" 开头,那为什么不呢

    df.gender.str[7:]
    

    pandas.Series.map

    我不喜欢其他选项,因为它们都涉及字符串操作。您可以更明确地使用字典映射并保持恒定时间查找

    df.gender.map({'mostly_male': 'male', 'mostly_female': 'female'})
    

    时间

    设置

    df = pd.DataFrame(dict(gender=[f"mostly_{g}" for g in ['male', 'female'] * 10000]))
    

    测试

    %timeit df.replace({'gender': {'mostly_': ''}}, regex=True)
    %timeit df.gender.str.replace('mostly_', '')
    %timeit df.gender.str[7:]
    %timeit df.gender.map({'mostly_male': 'male', 'mostly_female': 'female'})
    
    100 loops, best of 3: 12.8 ms per loop
    100 loops, best of 3: 16.1 ms per loop
    100 loops, best of 3: 5.42 ms per loop
    1000 loops, best of 3: 1.8 ms per loop
    

    【讨论】:

    • 为速度投票 :-)
    • 谢谢@Wen (-:
    【解决方案2】:

    你应该使用替换:

     df['gender'] = df['gender'].str.replace('mostly_', '')
    

    这会将“mostly_”的任何完全匹配项替换为空白“”。如果在您传递的字符串中找到任何前导字符,您的示例将从行中删除前导字符。所以“m”被lstrip找到了,“mostly_”被去掉了,但是由于“male”中有一个“m”,它也会被去掉。

    【讨论】:

    【解决方案3】:

    您可以使用replace 删除不需要的字符串。 lstrip 将删除所有符合条件的字符。详情lstrip docs 也可以使用正则表达式库替换子字符串

    import re
    df['gender'].map(lambda x: re.sub('^mostly_','',x))
    

    【讨论】:

      猜你喜欢
      • 2020-06-02
      • 1970-01-01
      • 2011-04-25
      • 1970-01-01
      • 2013-10-04
      • 2020-06-15
      • 1970-01-01
      • 2017-04-18
      • 1970-01-01
      相关资源
      最近更新 更多