加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 使用部分datetime索引连接数据帧

发布时间:2020-12-20 12:01:03 所属栏目:Python 来源:网络整理
导读:我有两个带有日期时间索引的数据帧. import pandas as pdd = {'dat': ['2016-01-01','2016-01-02','2016-01-03','2017-01-01','2017-01-02','2017-01-03'],'x': [1,2,3,4,5,6]}df1 = pd.DataFrame(d)df1.set_index(['dat'],inplace=True)df1.index = pd.to_d
我有两个带有日期时间索引的数据帧.

import pandas as pd

d = {'dat': ['2016-01-01','2016-01-02','2016-01-03','2017-01-01','2017-01-02','2017-01-03'],'x': [1,2,3,4,5,6]}
df1 = pd.DataFrame(d)
df1.set_index(['dat'],inplace=True)
df1.index = pd.to_datetime(df1.index)

d = {'dat': ['2016-01-01','2017-01-01'],'y': [10,11]}
df2 = pd.DataFrame(d)
df2.set_index(['dat'],inplace=True)
df2.index = pd.to_datetime(df2.index)

DF1:

x
dat          
2016-01-01  1
2016-01-02  2
2016-01-03  3
2017-01-01  4
2017-01-02  5
2017-01-03  6

DF2:

y
dat           
2016-01-01  10
2017-01-01  11

我想只使用索引的年份和月份加入他们.
所以输出结果如下:

DF3:

x  y
dat          
2016-01-01  1  10 
2016-01-02  2  10
2016-01-03  3  10
2017-01-01  4  11
2017-01-02  5  11
2017-01-03  6  11

我试图加入他们

df1.join(df2,how='inner')

而且我知道我可以像这样提取年份和月份:

df1.index.map(lambda x: x.strftime('%Y-%m'))
df2.index.map(lambda x: x.strftime('%Y-%m'))

但我想知道如何将所有这些结合起来以达到预期的效果?

非常感谢

解决方法

您要合并的信息未在任何地方明确定义.当我们合并而不破坏它时,没有很好的方法可以将日期保留在索引中.因此,我们将索引移动到适当的数据框并创建两个要合并的新列.即,年和月.我将这部分包装在一个函数中,以便更好地了解发生了什么.

def f(df):
    df = df.reset_index()
    return df.assign(year=df.dat.dt.year,month=df.dat.dt.month)

df = f(df1).merge(f(df2),on=['year','month'],suffixes=['','_'])

df.set_index('dat')[['x','y']]

            x   y
dat              
2016-01-01  1  10
2016-01-02  2  10
2016-01-03  3  10
2017-01-01  4  11
2017-01-02  5  11
2017-01-03  6  11

这是使用pd.Index.map和to_period的不同概念.从df2创建字典映射,将年/月期对象转换为y列中的对应值.然后使用map将df1.index中的周期化日期映射到正确的y值.

m = dict(zip(df2.index.to_period('M'),df2.y))
df1.assign(y=df1.index.to_period('M').map(m.get))

            x   y
dat              
2016-01-01  1  10
2016-01-02  2  10
2016-01-03  3  10
2017-01-01  4  11
2017-01-02  5  11
2017-01-03  6  11

建立

dates1 = ['2016-01-01','2017-01-03']
df1 = pd.DataFrame({'x': range(1,7)},pd.DatetimeIndex(dates1,name='dat'))

dates2 = ['2016-01-01','2017-01-01']
df2 = pd.DataFrame({'y': [10,11]},pd.DatetimeIndex(dates2,name='dat'))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读