Search code examples
pythonpandasstringfor-loopsplit

For loop to convert strings based on last word not running


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.


Solution

  • 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)