我有一个包含以下列的数据框:
日期 | 压缩 | 价钱 | |
---|---|---|---|
0 | 2019-01-01 | 90102 | 58.02 |
1个 | 2019-01-01 | 90102 | 81.55 |
2 | 2019-01-01 | 90102 | 11.97 |
3 | 2019-01-01 | 90102 | 93.23 |
4 | 2019-01-01 | 90103 | 13.68 |
我要创建第4列,该列应具有基于该邮政编码中的最高价格和该日期的价格比率。
所以我用了另一个叫做df_max_price的df
df_max_price = df.groupby(['Date','Zip'], as_index=False)['Price'].max()
日期 | 压缩 | 价钱 | |
---|---|---|---|
0 | 2019-01-01 | 90102 | 93.23 |
1个 | 2019-01-01 | 90103 | 13.68 |
现在我想在df中添加一个新列,该列应为该日期和邮政编码的Price和maxprice的比率
日期 | 压缩 | 价钱 | 比 | |
---|---|---|---|---|
0 | 2019-01-01 | 90102 | 58.02 | 0.622 |
1个 | 2019-01-01 | 90102 | 81.55 | 0.875 |
2 | 2019-01-01 | 90102 | 11.97 | 0.128 |
3 | 2019-01-01 | 90102 | 93.23 | 1.000 |
4 | 2019-01-01 | 90103 | 13.68 | 1.000 |
计算基于58.02/93.23
,依此类推。
有人可以帮我展示如何使用lambda函数完成它。
使用groupby
和transform
df['ratio'] = df['Price'] / df.groupby(['Date','Zip'], as_index=False)['Price'].transform('max')['Price']
Date Zip Price ratio
0 2019-01-01 90102 58.02 0.622332
1 2019-01-01 90102 81.55 0.874718
2 2019-01-01 90102 11.97 0.128392
3 2019-01-01 90102 93.23 1.000000
4 2019-01-01 90103 13.68 1.000000
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句