Jack
Jack

Reputation: 413

Apply function to specific row in dataframe

I have a dataframe of which I want to clean up a specific row, in this case the first row. I have written a function in which I believe will return the string if the regex is matched.

def clean_cells(string):
    if '201' in string:
        return re.findall('201[0-9]', string)[0]
    else:
        return string

I want to apply this function to the first row in the dataframe then replace the first row with the cleaned up version then contatenate the rest of the original dataframe.

I have tried:

df = df.iloc[[0]].apply(clean_cells)

Upvotes: 1

Views: 234

Answers (1)

jezrael
jezrael

Reputation: 863791

Select first row by position and all columns with : and assign back:

df.iloc[0, :] = df.iloc[0, :].apply(clean_cells)

Another solution:

df.iloc[0] = df.iloc[0].apply(clean_cells)

Upvotes: 2

Related Questions