Skip to main content
 首页 » 编程设计

Python pandas asof 加入群组

2024年10月24日10yjmyzz

我有两个 pandas 数据框 X 和 Y,每个都包含过去一个月的日内价格和时间数据。我想在 X 上运行 Y 的连接,即每次我们看到 X 的更新时我们都采用 Y 的现行价格。我想运行日内分析(因为隔夜效应)

我现在的代码是

Y_asof = Y.groupby('Date').apply(lambda x: x.asof(X.index)) 

但是,这会返回一个错误,说明

AttributeError: 'DataFrame' object has no attribute 'asof' 

当我运行时它正在工作

Y_asof = Y.apply(lambda x: x.asof(X.index)) 

X的样本数据:

                                 Mid        Date 
Time                                             
2015-09-15 13:02:03.000049  7.575392  2015-09-15 
2015-09-15 13:02:06.000049  7.575521  2015-09-15 
2015-09-15 13:02:08.000049  7.575392  2015-09-15 
2015-09-15 13:02:14.000049  7.575521  2015-09-15 
2015-09-15 13:02:15.000048  7.575649  2015-09-15 

Y的样本数据:

                                 Mid        Date 
Time                                             
2015-09-15 12:00:00.443000  4.650894  2015-09-15 
2015-09-15 12:00:00.443000  4.650899  2015-09-15 
2015-09-15 12:00:06.321000  4.650894  2015-09-15 
2015-09-15 12:00:06.322000  4.650884  2015-09-15 
2015-09-15 12:00:10.839000  4.650894  2015-09-15 

有人可以帮忙吗?非常感谢!

请您参考如下方法:

asof是 Series 方法,而不是 DataFrame 方法。它适用于时间列:

In [11]: Y.groupby('Date').apply(lambda x: x["Time"].asof(X.index)) 
Out[11]: 
Time                                 0                           1                           2                           3                           4 
Date 
2015-09-15  2015-09-15 12:00:00.443000  2015-09-15 12:00:00.443000  2015-09-15 12:00:06.321000  2015-09-15 12:00:06.322000  2015-09-15 12:00:10.839000 

当您执行应用时,它跨越每一行(这是一个系列)。