i'm trying to do something like this:
d={'Month':['January','February','March','April'], 'Saves':[2000, 2100, 1900, 1500]}
saves=pd.DataFrame(data=d)
and turns like this:
Month Saves
0 January 2000
1 February 2100
2 March 1900
3 April 1500
What i would like is to create a new column 'Spent' with the logic: if the value of the last month is more ->"Yes", else -> 'No', like:
Month Saves Spent
0 January 2000 -
1 February 2100 No
2 March 1900 Yes
3 April 1500 Yes
I have no idea how to do it, tried iterating in many ways, but it didn't work.
Thanks!
You can use shift to access the next column
saves['Spent'] = np.where(saves['Saves'] < saves['Saves'].shift(), 'Yes', 'No')
Month Saves Spent
0 January 2000 No
1 February 2100 No
2 March 1900 Yes
3 April 1500 Yes
Notice , here the first row need to be treated differently
saves.at[1:,'Spent']=saves.Saves.diff().gt(0).map({True:'No',False:'Yes'}).iloc[1:]
saves
Out[190]:
Month Saves Spent
0 January 2000 NaN
1 February 2100 No
2 March 1900 Yes
3 April 1500 Yes
saves.fillna('')
Out[191]:
Month Saves Spent
0 January 2000
1 February 2100 No
2 March 1900 Yes
3 April 1500 Yes
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.