dsugasa dsugasa - 15 days ago 8
Python Question

Applying a function to only part of a Pandas Dataframe columns

I have a Dataframe that looks like this:

Date Last
2016-11-03 101.58
2016-11-04 100.50
2016-11-07 103.55
2016-11-08 104.63
2016-11-09 106.15
2016-11-10 107.65
2016-11-11 106.74
2016-11-14 108.22
2016-11-15 107.92
2016-11-16 106.03


and a simple function:

def new_def(x):
add=70.00
return x[0]+add


I want to add another column to the dataframe using the function, but I only want to apply it to dates prior to '2016-11-09'. I've tried doing this with:

df['New']= df[:'2016-11-09'].apply(new_def, axis=1)


The resulting column is correct up to '2016-11-09' and NaN afterwards. Any suggestions on how to return 'x[0] + add' prior to '2016-11-09' and 'x[0]' afterwards?

thanks in advance

Answer

You could rewrite your new_def function to take a date parameter:

def new_def(val, date):
    return val+70.0 if date < pd.datetime(2016, 11, 9) else val

And then apply it like this:

df.apply(lambda r: newdef(r['Last'], r.name), 1)