我有两个数据帧 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 的内部连接,这样如果 df1 中对应于 df2 中的小时数的日期可用,我们认为内部连接为 true,否则为 false。
我想获得两个 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 in1d 和 pandas normalize 函数以冗长的方式完成这项任务。我一直在寻找实现这一目标的 pythonic 方式。
请您参考如下方法:
考虑一个如图所示构造的虚拟 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()
获取仅考虑匹配日期作为区分参数的公共(public)索引。
intersect = pd.Index(df2.index.date).intersection(df1.index)
第一个公共(public)索引 DF 包含其原始数据帧的列:
df11 = df1.loc[intersect]
df11
第二个公共(public)索引 DF 包含其原始数据帧的列:
df22 = df2.iloc[np.where(df2.index.date.reshape(-1,1) == intersect.values)[0]]
df22
