我根据日期有两个数据框,例如: df1
id date time sum
abc 15/03/2020 01:00:00 15
abc 15/03/2020 02:00:00 25
abc 15/03/2020 04:00:00 10
xyz 15/03/2020 12:00:00 30
xyz 15/03/2020 03:00:00 20
df2
id date sum_last
abc 14/03/2020 10
xyz 14/03/2020 20
如果总和行的值大于前一个总和行的值,我想通过比较总和列的值在 df1 中创建一列 Flag 标志是 1 否则它的 0 但对于总和列值的第一行 15它不会是 Nan,它将与 df2 sum value 的值进行比较,因为它对于一个较小的日期(即 2020 年 3 月 14 日)具有相同的 ID。因此输出将是:
id date time sum Flag
abc 15/03/2020 01:00:00 15 1
abc 15/03/2020 02:00:00 25 1
abc 15/03/2020 04:00:00 10 0
xyz 15/03/2020 12:00:00 30 1
xyz 15/03/2020 03:00:00 20 0
任何人都可以帮助我加入这两个 dfs 并根据 id 列将 df2 的值与 df1 的 sum 列的第一个值进行比较来获得准确的结果。提前致谢
答案 0 :(得分:0)
使用:
print (df1)
id date time sum sum1
0 abc 15/03/2020 01:00:00 15 10
1 abc 15/03/2020 02:00:00 25 10
2 abc 15/03/2020 04:00:00 10 10
3 xyz 15/03/2020 12:00:00 30 10
4 xyz 15/03/2020 03:00:00 20 10
print (df2)
id date sum sum1
0 abc 15/03/2020 10 0
1 xyz 14/03/2020 20 100
#columns for processing
cols = ['sum','sum1']
#columnsnames in df2
new = [x + '_last' for x in cols]
#dictionary for rename for match with df1.columns
d = dict(zip(new, cols))
print (d)
#set id to index
df1 = df1.set_index('id')
df2 = df2.set_index('id')
#shifting per id and first NaN repalced by df2
df = df1.groupby('id')[cols].shift().fillna(df2.rename(columns=d)[cols])
print (df)
sum sum1
id
abc 10.0 0.0
abc 15.0 10.0
abc 25.0 10.0
xyz 20.0 100.0
xyz 30.0 10.0
#comapred and added to df1
df1 = pd.concat([df1, df1[cols].gt(df[cols]).astype(int).add_prefix('flag_')], axis=1)
print (df1)
date time sum sum1 flag_sum flag_sum1
id
abc 15/03/2020 01:00:00 15 10 1 1
abc 15/03/2020 02:00:00 25 10 1 0
abc 15/03/2020 04:00:00 10 10 0 0
xyz 15/03/2020 12:00:00 30 10 1 0
xyz 15/03/2020 03:00:00 20 10 0 0