user3294779 user3294779 - 16 days ago 5
Python Question

modify string values in dataframe column

I'm trying to modify the string values in a dataframe column. So far I have tried this:

def years(x):
x = x.split(' ')[0]
x = x[-2:]
return x

df['Date'].apply(years)


When I run this and then take a look at the dataframe the actual df['Date'] column is unmodified.

For reference, I'm trying to change the column values from a string that looks like this, '12/21/15 20:30', into a string (or integer) that just includes the year, so in this case, '15'.

Answer

You need to assign the returned value to a new column. .apply does not operate in-place.

def years(x):
x = x.split(' ')[0]
x = x[-2:]
return x

df['NewDate'] = df['Date'].apply(years)
Comments