Home > database >  For loop to convert strings based on last word not running
For loop to convert strings based on last word not running

Time:02-05

I am trying to write a for-loop in python on a pandas dataframe. I want to convert all strings in the color column that have "Green" as their last word (ex. Yellowish Green") to just "Green". Below is my loop:

for color in df['color']:
    low = color.split()
    if low[-1] == "Green":
        color = "Green"

However, this is not changing the actual values in the dataframe.

CodePudding user response:

You can do:

def transform(string):
    last_word = string.split()[-1]
    if last_word.lower() == 'green':
        return 'green'
    else:
        return string

df['color'] = df['color'].apply(transform)

CodePudding user response:

For loops in Python iterate over the values and not references of whatever you're iterating over. You could use list comprehensions instead:

df['color'] = ["Green" if x.split()[-1] == "Green" else x for x in df['color']]

Or if the word green isn't necessarily capitalized:

df['color'] = ["Green" if x.split()[-1].lower() == "green" else x for x in df['color']]
  • Related