如何与Groupby一起使用Sklearn Standardardscaler?
我正在尝试根据日期对大熊猫的数据框架进行标准化。
My dataset looks like this:
date | permno | ret | cumret | mom1m | mom3m | mom6m |
---|---|---|---|---|---|---|
2004-01-30 | 80000 | 0.053 | 1.497 | 0.067 | 0.140 | 0.137 |
2004-02-29 | 80000 | 0.053 | 1.497 | 0.067 | 0.140 | 0.137 |
2004-03-31 | 80000 | 0.053 | 1.497 | 0.067 | 0.140 | 0.137 |
2004-01- 30 | 80001 | 0.053 | 1.497 | 0.067 | 0.140 | 0.137 |
2004-02-29 | 80001 | 0.053 | 1.497 | 0.067 | 0.140 0.140 | 0.137 |
2004-03-31 | 80001 | 0.053 1.497 0.067 | 0.067 | 0.140 | 0.140 | 0.137 |
我试图缩放代码>,MOM6M
基于日期。
因此,第一行应用第四行缩放,第二行应用第5行缩放,第三行应用最后一行缩放。
我尝试的是
crsp2[scale_cols] = crsp2.groupby('date')[scale_cols].apply(lambda x: StandardScaler().fit_transform(x))
crsp2
是我要缩放的数据框架,而scale_cols
是我要扩展的功能列表。
I'm trying to normalize a pandas dataframe while grouping it based on the dates.
My dataset looks like this:
date | permno | ret | cumret | mom1m | mom3m | mom6m |
---|---|---|---|---|---|---|
2004-01-30 | 80000 | 0.053 | 1.497 | 0.067 | 0.140 | 0.137 |
2004-02-29 | 80000 | 0.053 | 1.497 | 0.067 | 0.140 | 0.137 |
2004-03-31 | 80000 | 0.053 | 1.497 | 0.067 | 0.140 | 0.137 |
2004-01-30 | 80001 | 0.053 | 1.497 | 0.067 | 0.140 | 0.137 |
2004-02-29 | 80001 | 0.053 | 1.497 | 0.067 | 0.140 | 0.137 |
2004-03-31 | 80001 | 0.053 | 1.497 | 0.067 | 0.140 | 0.137 |
I'm trying to scale mom1m
, mom3m
, mom6m
based on the dates.
So the first row should be scaled with the 4th row, the second row should be scaled with the 5th row, the third row should be scaled with the last row.
What I've tried is
crsp2[scale_cols] = crsp2.groupby('date')[scale_cols].apply(lambda x: StandardScaler().fit_transform(x))
where crsp2
is the dataframe i'm trying to scale and scale_cols
is the list of features I'm trying to scale.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个简单的解决方案可以使用 “>标准标准。
您的代码看起来像这样:
输出:
A simpler solution could use
scale()
the pipelined version of the StandardScaler.Your code would look like this:
Output:
感谢此答案,您可以使用以下示例代码来完成您想要的事情。
Thank to this answer, you can do what you want with the below example code.