![](/img/trans.png)
[英]how to check whether the id in df1 existed in df2 when date in df2 is older than date in df1 and add new column accordingly using pandas
[英]Add column from df1 into df2 based on the Date column and fill na if df1 [Date] entries are missing
我有df1
具有 850 行和列名['Date', 'A']
数据框。 我也有df2
900 行和列名['Date', 'B', 'C', 'D']
。
它们的行数不同是因为df1
缺少一些“日期”条目。 但是,df1['Date'] 中的所有条目都在 df2['Date'] 中。
问题:我想基于相同的['Date']
行将df1['A']
合并到df2
。 合并后,我希望生成的df2['A']
为df1
中缺少['Dates']
的所有行反映一个 'na' 。
我尝试df2=pd.merge(df2, df1, on="Date")
但我得到的结果df2
有 850 行,这似乎是删除了 df1 和 df2 之间不匹配的日期。 相反,我希望合并后的结果df2
为 900 行,并且不匹配的日期行应在 df2['A']` 中显示“na”。
如何做到这一点?
使用left
连接而不是inner
连接(默认行为)
IE,
new_df = pd.merge(df2, df1, on="Date", how='left')
用零填充NA
(如 OP 在评论中要求的那样),
new_df.fillna(0, inplace=True)
# new_df['column'] = new_df['column'].astype(np.float64) # to convert column to float
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.