PyBoss
PyBoss

Reputation: 631

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

I have a dataframe like below. If there's a character in the last position is a dot, I want to replace it as a character "K" , not sure how to add the condition in the replace function

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

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

Sample data

enter image description here

expected result

enter image description here

Upvotes: 2

Views: 1968

Answers (2)

furas
furas

Reputation: 142671

Without regex you could use .str.endswith('.') or .str[-1] == '.' to filter rows which need to replace last char

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

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

But problem is replace - it would replace all dots in text. It would need to use different method - get text without last char .str[:-1] and add new char + "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)

EDIT:

Similar method with apply() (also without regex)

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

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

Upvotes: 2

BigBen
BigBen

Reputation: 50008

Using regex to match the last character:

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

Upvotes: 4

Related Questions