在Python Pandas中,如何在一个datetime列上连接另一个由periodindex索引的数据帧?

2024-07-02 11:13:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧,df1,df2。在

df1有一列“date”,即datetime。df2由periodidex(时间段,而不是时间戳)索引。在

我希望我能以某种方式连接这两个数据帧,这样,对于df1的每一行,我将为df1['date']所属的periodindex选择的行(在df2中)添加df2的所有列。在

我希望这个问题足够清楚。我想我可以手动做一些循环来完成,但是如果有一种更有效的方法,使用一些pandas方法,我会非常感激的。在

提前谢谢!在

以下是df2的第一列,数据帧由一个称为“cuatrimestre”的周期索引索引:

                  dif_precio_vivienda  dif_rendimiento_ibex  \
cuatrimestre                                              
1995Q1                        NaN                   NaN   
1995Q2                   0.000000             -2.940238   
1995Q3                   0.007233             -0.500118   
1995Q4                   0.026514              0.535169   
1996Q1                  -0.009417             -0.171129 

下面是df1的第一列:

^{pr2}$

您可以看到索引是不同的,但是它有一个datetime列('fecha'),我想在periodix上加入这个列。。。在


Tags: 数据方法datetimedate方式时间手动nan
1条回答
网友
1楼 · 发布于 2024-07-02 11:13:15

我想您可以先在DataFrames中的year和{}创建列DataFrames,在{}和{a3}中,通过df2中的^{}转换成{}。然后您可以按列year和{}对它们进行^{}

#if type of column fecha is to datetime, convert it
df1['fecha'] = pd.to_datetime(df1['fecha'])
df1['year'] = df1['fecha'].dt.year
df1['quarter'] = df1['fecha'].dt.quarter
print df1
           fecha  municipioid   latitud  longitud  numbanyo  numdormitorio  \
25138 2014-02-12         4353  0.705444 -0.064720       1.0            1.0   
25144 2014-05-06         4353  0.705444 -0.064720       1.0            1.0   
25185 2014-01-02         4353  0.705349 -0.064618       1.0            1.0   
25186 2014-02-12         4353  0.705353 -0.064620       1.0            1.0   
25201 2014-07-07         4353  0.705314 -0.064610       1.0            3.0   

       year  quarter  
25138  2014        1  
25144  2014        2  
25185  2014        1  
25186  2014        1  
25201  2014        3  

df2 = df2.reset_index()
df2[['year','quarter']] = df2['cuatrimestre'].str.split('Q', expand=True)
df2['year'] = df2['year'].astype(int)
df2['quarter'] = df2['quarter'].astype(int)
print df2
  cuatrimestre  dif_precio_vivienda  dif_rendimiento_ibex  year  quarter
0       2014Q1                  NaN                   NaN  2014        1
1       2014Q2             0.000000             -2.940238  2014        2
2       1995Q3             0.007233             -0.500118  1995        3
3       1995Q4             0.026514              0.535169  1995        4
4       1996Q1            -0.009417             -0.171129  1996        1
^{pr2}$

相关问题 更多 >