【问题标题】:Inner join of dataframes based on datetime基于日期时间的数据帧的内部连接
【发布时间】:2017-04-13 16:05:36
【问题描述】:

我有两个数据框 df1 和 df2。

df1.index
DatetimeIndex(['2001-09-06', '2002-08-04', '2000-01-22', '2000-12-19',
               '2008-02-09', '2010-07-07', '2011-06-04', '2007-03-14',
               '2003-05-17', '2016-02-27',..dtype='datetime64[ns]', name=u'DateTime', length=6131, freq=None)

df2.index
DatetimeIndex(['2002-01-01 01:00:00', '2002-01-01 10:00:00',
               '2002-01-01 11:00:00', '2002-01-01 12:00:00',
               '2002-01-01 13:00:00', '2002-01-01 14:00:00',..dtype='datetime64[ns]', length=129273, freq=None)

即df1 的索引为天,df2 的索引为日期时间。我想在索引上执行 df1 和 df2 的内部连接,这样如果 df2 中对应于小时的日期在 df1 中可用,我们认为内部连接为真,否则为假。

我想获得两个 df11 和 df22 作为输出。 df11 将具有来自 df1 的公共日期和相应列。 df22 将具有来自 df2 的通用日期时间和相应的列。

例如df1 中的“2002-08-04”和 df2 中的“2002-08-04 01:00:00”被认为存在于两者中。

如果 df1 中的“1802-08-04”在 df2 中没有小时,则它在 df11 中不存在。

但是,如果 df2 中的“2045-08-04 01:00:00”在 df1 中没有日期,则它在 df22 中不存在。

现在我正在使用numpy in1dpandas normalize 函数来完成这项任务。我一直在寻找 pythonic 方法来实现这一点。

【问题讨论】:

  • 你能把得到的代码贴出来吗?这会让你想要做的事情更加明显。

标签: python pandas dataframe


【解决方案1】:

考虑如下构造的虚拟DF

idx1 = pd.date_range(start='2000/1/1', periods=100, freq='12D')
idx2 = pd.date_range(start='2000/1/1', periods=100, freq='300H')
np.random.seed([42, 314])

DF 包含 DateTimeIndex 作为唯一的日期属性:

df1 = pd.DataFrame(np.random.randint(0,10,(100,2)), idx1)
df1.head()

DF 包含DateTimeIndex 作为日期+时间属性:

df2 = pd.DataFrame(np.random.randint(0,10,(100,2)), idx2)
df2.head()

获取公共索引,仅考虑匹配日期作为区分参数。

intersect = pd.Index(df2.index.date).intersection(df1.index)

第一个公共索引 DF 包含其原始数据框的列:

df11 = df1.loc[intersect]
df11

第二个公共索引 DF 包含其原始数据框的列:

df22 = df2.iloc[np.where(df2.index.date.reshape(-1,1) == intersect.values)[0]]
df22

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-08
    • 2019-10-28
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    相关资源
    最近更新 更多