简体   繁体   English

比较两个不同维度的数据框

[英]Comparing Two Dataframes with different dimensions

Using this as a starting point:以此为起点:

a=[['username1','Tesco','09:28:27'],['username2','Target','09:01:10'],['username3','Lily','08:27:48']]
df_a=pd.DataFrame(a,columns=['username','pos_name','end_visit'])

b=[['Done','2022-03-13','09:28:00'],['Done','2022-03-13','09:01:00'],['Done','2022-03-13','08:42:00'],['Done','2022-03-13','08:27:00']]
df_b=pd.DataFrame(b,columns=['planogramme','date','hour'])

The result is 2 dataframes that looks like this:结果是 2 个数据帧,如下所示:

username    pos_name    end_visit
0   username1   Tesco   09:28:27
1   username2   Target  09:01:10
2   username3   Lily    08:27:48

    planogramme date    hour
0   Done    2022-03-13  09:28:00
1   Done    2022-03-13  09:01:00
2   Done    2022-03-13  08:42:00
3   Done    2022-03-13  08:27:00

As you can see,it's not the same dimensions and i want to actually compare the hour of 'df_b' with the 'end_visit' of 'df_a', if they are the same i want to create a new column on 'df_a' and copy the value of df_a['planogramme'],in the end it would need to look like something like this如您所见,它的尺寸不同,我想实际比较“df_b”的时间和“df_a”的“end_visit”,如果它们相同,我想在“df_a”上创建一个新列并复制df_a['planogramme'] 的值,最后它需要看起来像这样

 username   pos_name    end_visit   plannograme_done
    0   username1   Tesco   09:28:27   Done
    1   username2   Target  09:01:10   Done
    2   username3   Lily    08:27:48   Done

The problem is that for username3 for example,it needs to iterate over all the rows of 'df_b' and not return the value of the 2nd row but rather the 3rd one.问题是,例如,对于 username3,它需要遍历“df_b”的所有行,而不是返回第 2 行的值,而是返回第 3 行的值。

The easiest approach would be to extract the hour from df_a:最简单的方法是从 df_a 中提取hour

df_a['hour'] = df_a['end_visit'].str[:5]+':00'
df_a
    username    pos_name    end_visit   hour
0   username1   Tesco   09:28:27    09:28:00
1   username2   Target  09:01:10    09:01:00
2   username3   Lily    08:27:48    08:27:00

Then merge df_a and df_b on hour :然后在hour合并df_adf_b

df_a.merge(df_b, on = 'hour')

Output: Output:

username    pos_name    end_visit   hour    planogramme date
0   username1   Tesco   09:28:27    09:28:00    Done    2022-03-13
1   username2   Target  09:01:10    09:01:00    Done    2022-03-13
2   username3   Lily    08:27:48    08:27:00    Done    2022-03-13

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM