I want to create a new column that outputs ascending or descending depending on values in other columns
Index Leg Map Number
0 AD J1 1
1 AD J1 2
2 AD J1 3
3 AD J2 5
4 AD J2 3
4 AF J1 9
5 AF J1 6
So looking at this dataframe, I want to create a new column "updown" that is either ascending or descending depending based on the leg, map and number columns. Basically for every leg and map pairings, look at the number column in order to determine whether the numbers are ascending or descending....which will result in a dataframe like:
Index Leg Map Number Updown
0 AD J1 1 ascending
1 AD J1 2 ascending
2 AD J1 3 ascending
3 AD J2 5 descending
4 AD J2 3 descending
4 AF J1 9 descending
5 AF J1 6 descending
Any help will be appreciated
IIUC, you need:
s=df.groupby(['Leg','Map'])['Number'].transform(lambda x: (x.diff()>0).any())
Or:
s=df.groupby(['Leg','Map'])['Number'].transform(lambda x: x.is_monotonic) #thanks Mark Wang
df['Updown']=np.where(s,'ascending','descending')
print(df)
Index Leg Map Number Updown
0 0 AD J1 1 ascending
1 1 AD J1 2 ascending
2 2 AD J1 3 ascending
3 3 AD J2 5 descending
4 4 AD J2 3 descending
5 4 AF J1 9 descending
6 5 AF J1 6 descending
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.