【问题标题】:how to replace characters in a dataframe where column may have different data types entries如何替换列可能具有不同数据类型条目的数据框中的字符
【发布时间】:2020-12-02 21:26:53
【问题描述】:

python 新手想问一个关于如何同时替换多个字符的问题,因为这些条目可能具有不同的数据类型。我只想更改字符串并保持其他所有内容不变:

import pandas as pd

def test_me(text):
    replacements = [("ID", ""),("u", "a")] # 
    return [text.replace(a, b) for a, b in replacements if type(text) == str]

cars = {'Brand': ['HonduIDCivic', 1, 3.2,'CarIDA4'],
        'Price': [22000,25000,27000,35000]
        }

df = pd.DataFrame(cars, columns = ['Brand', 'Price'])
df['Brand'] = df['Brand'].apply(test_me)

导致

    Brand                       Price
0   [HonduCivic, HondaIDCivic]  22000
1   []                          25000
2   []                          27000
3   [CarA4, CarIDA4]            35000

而不是

    Brand                       Price
0   HondaCivic                  22000
1   1                           25000
2   3.2                         27000
3   CarA4                       35000

感谢任何建议!

【问题讨论】:

    标签: python regex pandas


    【解决方案1】:

    如果替换永远不会有相同的搜索短语,则将元组列表转换为字典然后使用会更容易

    import re
    #...
    def test_me(text):
        replacements = dict([("ID", ""),("u", "a")])
        if type(text) == str:
            return re.sub("|".join(sorted(map(re.escape, replacements.keys()),key=len,reverse=True)), lambda x: replacements[x.group()], text)
        else:
            return text
    

    "|".join(sorted(map(re.escape, replacements.keys()),key=len,reverse=True)) 部分将从 re.escaped 字典键中创建一个以最长开头的正则表达式,以避免在处理共享相同前缀的嵌套搜索短语时出现问题。

    熊猫测试:

    >>> df['Brand'].apply(test_me)
    0    HondaCivic
    1             1
    2           3.2
    3         CarA4
    Name: Brand, dtype: object
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 2019-09-02
      相关资源
      最近更新 更多