Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于唯一列值进行比较,并基于条件设置标志_Python_Pandas_Dataframe_Lambda_Pandas Groupby - Fatal编程技术网

Python 基于唯一列值进行比较,并基于条件设置标志

Python 基于唯一列值进行比较,并基于条件设置标志,python,pandas,dataframe,lambda,pandas-groupby,Python,Pandas,Dataframe,Lambda,Pandas Groupby,我对熊猫和数据帧非常陌生。我以前使用过SQL。我在下面附上了一张表: Sub DOB Groups Mean Val CheckVol 0 1112 1/1/1980 FirstVisit 6000 0 1 1121 2/2/1980 FirstVisit 6000 0 2 1138 3/3/1980 FirstVisit 6000 0 3 1227 4/4/

我对熊猫和数据帧非常陌生。我以前使用过SQL。我在下面附上了一张表:

    Sub     DOB         Groups      Mean Val  CheckVol
0   1112    1/1/1980    FirstVisit  6000      0
1   1121    2/2/1980    FirstVisit  6000      0
2   1138    3/3/1980    FirstVisit  6000      0
3   1227    4/4/1980    FirstVisit  6000      0
12  1443    1/1/1980    SecondVisit 5000      0
13  1443    2/2/1980    SecondVisit 5500      0
14  1481    3/3/1980    SecondVisit 6500      1
15  1482    4/4/1980    SecondVisit 5400      0
24  1483    2/2/1980    ThirdVisit  5400      0
25  1490    3/3/1980    ThirdVisit  5400      0
所以我想做的是根据DOB进行分组,因为这是唯一的比较平均val和首次就诊的方法。如果第二次就诊大于第一次就诊,则检查第三次就诊,如果第三次就诊小于第一次就诊,则更改标签。因此,在示例表中,将14组改为第三组,25组改为第二组。我在想,在本例中,可能会创建一个新列作为一个名为checkVol的标志,而案例14将有一个1。这就是我的观点,这是非常错误的:

checkVol = df.groupby('DOB').apply(lambda r: r)
#df.set_index('DOB', inplace=True)
df['checkVol'] = users
谢谢你的帮助


Kevin

IIUC,您可以
groupby
DOB
列中,然后在
Mean Val
列中使用您描述的条件进行变换。这将返回一个布尔列,因此您只需将其转换为
int

df['CheckVol'] = df.groupby('DOB')['Mean Val'].transform(lambda x: x > x.iloc[0]).astype(int)

>>> df
     Sub       DOB       Groups  Mean Val  CheckVol
0   1112  1/1/1980   FirstVisit      6000         0
1   1121  2/2/1980   FirstVisit      6000         0
2   1138  3/3/1980   FirstVisit      6000         0
3   1227  4/4/1980   FirstVisit      6000         0
12  1443  1/1/1980  SecondVisit      5000         0
13  1443  2/2/1980  SecondVisit      5500         0
14  1481  3/3/1980  SecondVisit      6500         1
15  1482  4/4/1980  SecondVisit      5400         0
24  1483  2/2/1980   ThirdVisit      5400         0
25  1490  3/3/1980   ThirdVisit      5400         0