gpt4 book ai didi

python - 在Python Pandas中,如何在日期时间列上加入另一个由周期索引索引的数据帧?

转载 作者:太空宇宙 更新时间:2023-11-03 16:44:35 25 4
gpt4 key购买 nike

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

df1 有一个“日期”列,即日期时间。 df2 通过 periodindex(时间段,而不是时间戳)进行索引。

我希望能够以某种方式连接两个数据帧,以便对于 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 的第一列:

    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

您可以看到索引不同,但它有一个日期时间列('fecha'),我想在 periodindex 上加入此列...

最佳答案

我认为您可以首先在两个 DataFrames 中创建列 yearquarter by dt.yearquarter在 df1 和 str.split 中通过 astype 转换为 int在 df2 中。然后你就可以merge季度列:

#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
print pd.merge(df1,df2, on=['year','quarter'], how='left')
fecha municipioid latitud longitud numbanyo numdormitorio year \
0 2014-02-12 4353 0.705444 -0.064720 1.0 1.0 2014
1 2014-05-06 4353 0.705444 -0.064720 1.0 1.0 2014
2 2014-01-02 4353 0.705349 -0.064618 1.0 1.0 2014
3 2014-02-12 4353 0.705353 -0.064620 1.0 1.0 2014
4 2014-07-07 4353 0.705314 -0.064610 1.0 3.0 2014

quarter cuatrimestre dif_precio_vivienda dif_rendimiento_ibex
0 1 2014Q1 NaN NaN
1 2 2014Q2 0.0 -2.940238
2 1 2014Q1 NaN NaN
3 1 2014Q1 NaN NaN
4 3 NaN NaN NaN

关于python - 在Python Pandas中,如何在日期时间列上加入另一个由周期索引索引的数据帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36443506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com