合并两个不相等的数据帧,两个索引(日期时间和日期)上具有部分相同的元素

时间:2019-09-29 18:13:32

标签: python pandas datetime merge

我想在两个部分具有相同元素的列上合并两个不同长度的数据帧。

left_dataframe(A)的索引为datetime类型,相同的日期将显示为倍数,但时间不同(因此,index.date无济于事)。

right_dataframe(B)的索引为datetime.date类型,并且每个日期都与预期的一样。

A=pd.DataFrame({'datetime':['2019-06-01 18:11:55', '2019-06-01 21:43:02','2019-07-23 09:07:18', '2019-07-24 10:32:24'], \
                'value 1':[2, 5, 80, 0]})

B=pd.DataFrame({'date':['2019-06-01', '2019-07-23', '2019-07-24'], \
                'value 2':[10, 7, 3]})

我需要合并两个日期数据框,特别是将B的元素放在第一个新日期出现的行上,并用0填充其余的相同日期-不同时间,所以输出应该是这样的(连同注释):

           datetime  value 1  value 2
2019-06-01 18:11:55        2       10  #this is the first 2019-06-01 --> so it got the value of dataframe B
2019-06-01 21:43:02        5        0  #this is the second 2019-06-01 --> so the value 2 column got filled in with a 0 value
2019-07-23 09:07:18       80        7
2019-07-24 10:32:24        0        3

您的投入不只欢迎^ _ ^

1 个答案:

答案 0 :(得分:1)

使用:

#convert columns to dates
B['date'] = pd.to_datetime(B['date']).dt.date
#convert to columns datetimes
A['datetime'] = pd.to_datetime(A['datetime'])

创建新列-Series.dt.datedatedatetimeA s中的B['date'] s,以date进行匹配,helper列以{{ {} {3}}中的1}}秒:

A['date'] = A['datetime'].dt.date
A['g'] = A.groupby('date').cumcount()
B['g'] = B.groupby('date').cumcount()

#print (A)
#print (B)

然后将GroupBy.cumcount与两列和左连接一起使用,删除帮助程序列,并通过DataFrame.merge将添加的列的缺失值转换为0

df = A.merge(B, on=['date','g'], how='left').drop(['date','g'], axis=1)
df['value 2'] = df['value 2'].fillna(0, downcast='int')
print (df)
             datetime  value 1  value 2
0 2019-06-01 18:11:55        2       10
1 2019-06-01 21:43:02        5        0
2 2019-07-23 09:07:18       80        7
3 2019-07-24 10:32:24        0        3
相关问题