【问题标题】:replace value in one column without using replace() function在不使用 replace() 函数的情况下替换一列中的值
【发布时间】:2022-02-19 03:52:34
【问题描述】:

我想在不使用replace() 函数的情况下替换字符串。
只想用pandasnumpy

样本数据:

# df
Col1
ab1
de4

替换的逻辑是:

  1. a 将是 i
  2. b 将是 g
  3. d 将是 m
  4. e 将是 t
  5. 1 将是 2
  6. 4 将是 3

有什么方法可以创建字典并使用它来识别和替换?

# df
Col1   Col2
ab1    ig2
de4    mt3

【问题讨论】:

标签: python pandas data-manipulation


【解决方案1】:

您可以使用translate

mapping = 'abde14'.maketrans({
    'a': 'i',
    'b': 'g',
    'd': 'm',
    'e': 't',
    '1': '2',
    '4': '3'
})

df['Col2'] = df.Col1.str.translate(mapping)

如果它总是映射到 1 个字符,则此语法可能更紧凑。

mapping = str.maketrans('abde14', 'igmt23')

【讨论】:

【解决方案2】:

您可以为其创建函数并使用 apply。

import pandas as pd

df = pd.DataFrame()
df['col'] = ['asdsd', 'xxx', '41xwqa']

def custom_replace(element):
    translate_dict = {
        'a': 'i',
        'b': 'g',
        'd': 'm',
        'e': 't',
        '1': '2',
        '4': '3'
    }
    return_element = ''
    for char in element:
        try:
            return_element += translate_dict[char]
        except:
            return_element += char
    return return_element

df['col'].apply(custom_replace)

【讨论】:

    猜你喜欢
    • 2020-06-05
    • 2016-01-27
    • 1970-01-01
    • 2019-04-07
    • 2023-03-23
    • 2021-03-31
    • 2011-12-29
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多