I have this dataframe
import pandas as pd
df = pd.DataFrame({'Found':['A','A','A','A','A','B','B','B'],
'Date':['14/10/2021','19/10/2021','29/10/2021','30/09/2021','20/09/2021','20/10/2021','29/10/2021','15/10/2021','10/09/2021'],
'LastDayMonth':['29/10/2021','29/10/2021','29/10/2021','30/09/2021','30/09/2021','29/10/2021','29/10/2021','29/10/2021','30/09/2021'],
'Mark':[1,2,3,4,3,1,2,3,2]
})
print(df)
Found Date LastDayMonth Mark
0 A 14/10/2021 29/10/2021 1
1 A 19/10/2021 29/10/2021 2
2 A 29/10/2021 29/10/2021 3
3 A 30/09/2021 30/09/2021 4
4 A 20/09/2021 30/09/2021 3
5 B 20/10/2021 29/10/2021 1
6 B 29/10/2021 29/10/2021 2
7 B 15/10/2021 29/10/2021 3
8 B 10/09/2021 30/09/2021 2
based on this dataframe I need to create a new column that is the "Mark" of the last day of the month to form this new column.
that is, I need the value of the 'Mark' column of the last day of the month of each Found
how i did
mark_last_day = df.loc[df.apply(lambda x: x['Date']==x['LastDayMonth'], 1)]
df.merge(mark_last_day[['Found', 'LastDayMonth', 'Mark']],
how='left',
on=['Found', 'LastDayMonth'],
suffixes=('', '_LastDayMonth'))
# Output
Found Date LastDayMonth Mark Mark_LastDayMonth
0 A 14/10/2021 29/10/2021 1 3
1 A 19/10/2021 29/10/2021 2 3
2 A 29/10/2021 29/10/2021 3 3
3 A 30/09/2021 30/09/2021 4 4
4 A 20/09/2021 30/09/2021 3 4
5 B 20/10/2021 29/10/2021 1 2
6 B 29/10/2021 29/10/2021 2 2
7 B 15/10/2021 29/10/2021 3 2
So far so good but I'm having trouble creating a new column with the Mark_LastDayMonth of the previous month or I need the last day of the current month and the previous month how do i do it
Ex.
Found Date LastDayMonth Mark Mark_LastDayMonth Mark_LastDayPrevious_Month
0 A 14/10/2021 29/10/2021 1 3 4
1 A 19/10/2021 29/10/2021 2 3 4
2 A 29/10/2021 29/10/2021 3 3 4
3 A 30/09/2021 30/09/2021 4 4 x
4 A 20/09/2021 30/09/2021 3 4 x
5 B 20/10/2021 29/10/2021 1 2 1
6 B 29/10/2021 29/10/2021 2 2 1
7 B 15/10/2021 29/10/2021 3 2 1
8 B 10/09/2021 30/09/2021 1 1 x
CodePudding user response: