【问题标题】:Replace string while considering the last character (number) value在考虑最后一个字符(数字)值的同时替换字符串
【发布时间】:2021-12-30 06:04:04
【问题描述】:

我从 Python 开始。我需要根据条件替换“旧”列中的字符串。如果字符串的第一个字符是A,我需要将其替换为Z,但我还需要将最后一个字符的值加1

例如:

Old New
A2 Z3
C4 C4
B4 B4
A5 Z6
A1 Z2
df = pd.DataFrame({'Old': ['A2', 'C4', 'B4', 'A5'], 'New': ['Z3', 'C4', 'B4', 'Z6']})
df['New'] = df['Old'].str.replace('A','Z')

【问题讨论】:

    标签: python pandas string replace


    【解决方案1】:

    使用自定义函数:

    df['New'] = df['Old'].apply(lambda x: x if x[0] != 'A' else f'Z{int(x[1:])+1}')
    print(df)
    
    # Output:
      Old New
    0  A2  Z3
    1  C4  C4
    2  B4  B4
    3  A5  Z6
    

    【讨论】:

    • 完美,会学习 lambda
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    相关资源
    最近更新 更多