【问题标题】:Remove characters from a string in a dataframe从数据框中的字符串中删除字符
【发布时间】:2018-07-09 13:56:56
【问题描述】:

这里是python初学者。我想在特定条件下更改数据框中列中的一些字符。

数据框如下所示:

import pandas as pd
import numpy as np
raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'],
                      'age': [20, 19, 22, 21],
                      'favorite_color': ['blue (VS)', 'red', 'yellow (AG)', "green"],
                      'grade': [88, 92, 95, 70]}
df = pd.DataFrame(raw_data, index = ['0', '1', '2', '3'])
df

我的目标是在姓氏列中替换空格后跟括号和两个字母。

蓝色而不是蓝色 (VS)。

我必须删除 26 个字母变体,但只有一种格式:last_name 后跟空格,后跟括号,然后是两个字母,后跟括号。 据我了解,应该是在正则表达式中:

( \(..\)

我尝试使用 str.replace 但它仅适用于完全匹配并且它会替换整个值。 我也试过这个:

df.loc[df['favorite_color'].str.contains(‘VS’), 'favorite_color'] = ‘random’

它还替换了整个值。

我看到我只能重写值,但我也看到使用这个:

df[0].str.slice(0, -5)

我可以删除包含我的搜索的字符串的最后 5 个字符。

在我看来,我应该列出我想要删除的 26 个匹配项,并通过列解析以删除这些匹配项,同时保留之前的文本。我搜索了与我的问题类似的帖子,但找不到解决方案。你有什么方向的想法吗?

【问题讨论】:

    标签: python regex string python-3.x character


    【解决方案1】:

    您可以将str.replace"(\(.*?\))" 模式一起使用

    例如:

    import pandas as pd
    
    raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'],
                          'age': [20, 19, 22, 21],
                          'favorite_color': ['blue (VS)', 'red', 'yellow (AG)', "green"],
                          'grade': [88, 92, 95, 70]}
    df = pd.DataFrame(raw_data, index = ['0', '1', '2', '3'])
    df["newCol"] = df["favorite_color"].str.replace("(\(.*?\))", "").str.strip()
    print( df )
    

    输出:

       age favorite_color  grade              name  newCol
    0   20      blue (VS)     88    Willard Morris    blue
    1   19            red     92       Al Jennings     red
    2   22    yellow (AG)     95      Omar Mullins  yellow
    3   21          green     70  Spencer McDaniel   green
    

    【讨论】:

    • 非常感谢它的工作,我没有遇到 str.strip()。我得加班了!
    猜你喜欢
    • 2021-02-13
    • 2021-11-08
    • 1970-01-01
    • 2019-03-06
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多