Skip to main content
 首页 » 编程设计

python之在两个索引(日期时间和日期)上合并两个具有部分公共(public)元素的不相等数据帧

2024年11月01日12xxx_UU

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

left_dataframe (A) 的索引为 datetime type 和相同的日期会出现多个但时间不同(因此,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 

非常欢迎您的意见^_^

请您参考如下方法:

使用:

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

创建新列 - date 来自 A 中的 datetime by Series.dt.date用于匹配 B['date'] 和辅助列 用于由 date 的副本合并 GroupBy.cumcount :

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

然后使用DataFrame.merge使用两列和左连接,删除辅助列并将添加列的缺失值转换为 0 by Series.fillna :

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