[英]Python - Create a column based on multiple other columns in a dataframe
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. 因此,查看此数据框,我想创建一个新的列“ updown”,该列根据leg,map和number列是升序还是降序。 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: IIUC,您需要:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.