gpt4 book ai didi

python - 合并列不匹配的 pandas 数据框

转载 作者:太空宇宙 更新时间:2023-11-03 17:43:29 24 4
gpt4 key购买 nike

我在两个数据框中有不同的数据。两者都有两列,称为“日期”和与这些日期相对应的数据。然而,这两个日期的频率不同。

Dataframe1 包含月底的数据。所以每个月只有一篇文章。 Dataframe2 包含未均匀分隔的日期。也就是说,它可能包含同一个月的多个日期。例如,如果Dataframe1包含2014年4月30日,Dataframe2可能包含2014年5月1日、2014年5月7日和2014年5月22日。

我想以某种方式合并数据帧,以便与 2014 年 4 月 30 日对应的 Dataframe1 中的数据与 2014 年 5 月的所有日期相对应地显示在 Dataframe2 中。有什么简单的方法可以实现吗?

最佳答案

我的方法是为 df1 添加月份列,即当前月份 + 1(您需要将 12 月滚动到 1 月,这意味着用 13 代替 1)。然后,我将 df1 的索引设置为此“月份”列,并针对“日期”列的月份调用 df2 上的 map,这将执行查找并分配“val”值:

In [70]:
# create df1
df1 = pd.DataFrame({'date':[dt.datetime(2014,4,30), dt.datetime(2014,5,31)], 'val':[12,3]})
df1
Out[70]:
date val
0 2014-04-30 12
1 2014-05-31 3
In [74]:
# create df2
df2 = pd.DataFrame({'date':['01 May 2014', '07 May 2014', '22 May 2014', '23 Jun 2014']})
df2['date'] = pd.to_datetime(df2['date'], format='%d %b %Y')
df2
Out[74]:
date
0 2014-05-01
1 2014-05-07
2 2014-05-22
3 2014-06-23
In [75]:
# add month column, you'll need to replace 13 with 1 for December
df1['month'] = df1['date'].dt.month+1
df1['month'].replace(13,1)
df1
Out[75]:
date val month
0 2014-04-30 12 5
1 2014-05-31 3 6

In [76]:
# now call map on the month attribute and pass df1 with the index set to month
df2['val'] = df2['date'].dt.month.map(df1.set_index('month')['val'])
df2
Out[76]:
date val
0 2014-05-01 12
1 2014-05-07 12
2 2014-05-22 12
3 2014-06-23 3

关于python - 合并列不匹配的 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30145241/

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