繁体   English   中英

替换字符串中的最后一个字符,如果它是 dataframe 中的特定字符 Python Pandas

[英]Replace the last character in a string if it's a particular character in a dataframe Python Pandas

我有一个如下所示的 dataframe。 如果最后position中有一个字符是点,我想将其替换为字符“K”,不知道如何在替换function中添加条件

df = pd.DataFrame({ 'Mix':['572.7.','44.44','99']})

df['Mix'].str.replace('.','K',regex=False)

样本数据

在此处输入图像描述

预期结果

在此处输入图像描述

使用正则表达式匹配最后一个字符:

df['Mix'].str.replace('\.$','K',regex=True)

如果没有正则表达式,您可以使用.str.endswith('.').str[-1] == '.' 过滤需要替换最后一个字符的行

mask = df['Mix'].str.endswith('.')
#mask = (df['Mix'].str[-1] == '.')

df['Mix'][mask] = df['Mix'][mask]....

但问题是replace - 它会替换文本中的所有点。 它需要使用不同的方法 - 获取没有最后一个字符的文本.str[:-1]并添加新的字符+ "K"

df['Mix'][mask] = df['Mix'][mask].str[:-1] + 'K'

import pandas as pd

df = pd.DataFrame({ 'Mix':['572.7.','44.44','99']})

mask = df['Mix'].str.endswith('.')
#mask = (df['Mix'].str[-1] == '.')

df['Mix'][mask] = df['Mix'][mask].str[:-1] + 'K'

print(df)

编辑:

apply()类似的方法(也没有regex

def modify(text):
    if text.endswith('.'):
        text = text[:-1] + 'K'
    return text

df['Mix'] = df['Mix'].apply(modify)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM