[英]Merge 2 pandas data frames on multiple columns
I have 2 dataframes with one of them containing the prediction and actual values for the previous months.我有 2 个数据框,其中一个包含前几个月的预测值和实际值。 As shown below it has prediction from January and February.如下所示,它有 1 月和 2 月的预测。 The values for Febuary are Null.二月的值为空。
DF1 DF1
Date日期 | Key钥匙 | Value价值 | prediction预言 |
---|---|---|---|
1-1-21 1-1-21 | A一种 | 33211 33211 | 22123 22123 |
1-1-21 1-1-21 | BA文学士 | 43231 43231 | 32132 32132 |
1-1-21 1-1-21 | C C | 13431 13431 | 43432 43432 |
1-2-21 1-2-21 | A一种 | Nan南 | 23421 23421 |
1-2-21 1-2-21 | BA文学士 | Nan南 | 44443 44443 |
1-2-21 1-2-21 | C C | Nan南 | 32133 32133 |
The second dataframe has date, key and value for February.第二个数据框包含二月的日期、键和值。 I would like to merge them to form a new table with all actual values and a forecasts in one table我想将它们合并以形成一个新表,其中包含所有实际值和一个表中的预测
DF2 DF2
Date日期 | Key钥匙 | Value价值 |
---|---|---|
1-2-21 1-2-21 | A一种 | 33212 33212 |
1-2-21 1-2-21 | BA文学士 | 52121 52121 |
1-2-21 1-2-21 | C C | 23123 23123 |
I want to merge the Values on the key and date into the first table.我想将键和日期上的值合并到第一个表中。 Final should look like this最终应该是这样的
Date日期 | Key钥匙 | Value价值 | prediction预言 |
---|---|---|---|
1-1-21 1-1-21 | A一种 | 33211 33211 | 22123 22123 |
1-1-21 1-1-21 | BA文学士 | 43231 43231 | 32132 32132 |
1-1-21 1-1-21 | C C | 13431 13431 | 43432 43432 |
1-2-21 1-2-21 | A一种 | 33212 33212 | 23421 23421 |
1-2-21 1-2-21 | BA文学士 | 52121 52121 | 44443 44443 |
1-2-21 1-2-21 | C C | 23123 23123 | 32133 32133 |
I tried pd.merge
it creates a new column instead of join into one column and pd.join
but it does a left join and drops some of the prediction data.我试过pd.merge
它创建一个新列而不是加入一列和pd.join
但它执行左连接并删除一些预测数据。 combine first simply appends to the data结合首先简单地附加到数据
这可能是一种在一行(虽然很长)中完成的方法:
df1['Value'] = df1.apply(lambda row: row['Value'] if pd.notna(row['Value']) else df2[(df2['Date'] == row['Date']) & (df2['Key'] == row['Key'])].iloc[0]['Value'], axis=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.