python - 附加 2 个带有行和列子集的 pandas 数据帧
问题描述
我有2个这样的数据框
df = pd.DataFrame({"date":["2019-01-01", "2019-01-02", "2019-01-03", "2019-01-04"],
"A": [1., 2., 3., 4.],
"B": ["a", "b", "c", "d"]})
df["date"] = pd.to_datetime(df["date"])
df_new = pd.DataFrame({"date":["2019-01-02", "2019-01-03", "2019-01-04", "2019-01-05", "2019-01-06"],
"A": [2, 3.5, 4, 5., 6.],
"B": ["b", "c1", "d", "e", "f"]})
df_new["date"] = pd.to_datetime(df_new["date"])
所以,我的数据框看起来像这样
df
-----------------------
date A B
2019-01-01 1 a
2019-01-02 2 b
2019-01-03 3 c
2019-01-04 4 d
df_new
----------------------
date A B
2019-01-02 2 b
2019-01-03 3.5 c1
2019-01-04 4 d
2019-01-05 5 e
2019-01-06 6 f
从这些数据帧中,我想将 df 附加到具有特定条件的 df_new 如下:
在两个数据框中都有可用日期的任何行,我们在 df_new 中采用这些行
任何日期在 df 中可用但在 df_new 中不可用的行,我们在 df 中取这些行
最后我的预期输出看起来像这样
Expected output
----------------------
date A B
2019-01-01 1 a (take from df)
2019-01-02 2 b (take from df_new)
2019-01-03 3.5 c1 (take from df_new)
2019-01-04 4 d (take from df_new)
2019-01-05 5 e (take from df_new)
2019-01-06 6 f (take from df_new)
我可以考虑找到 2 个数据框之间的行差异,但是当我考虑到日期列时它不起作用。我可以有你的建议吗?谢谢你。
解决方案
按按列使用concat
和删除重复项,最后按按创建默认唯一索引值:date
DataFrame.drop_duplicates
DataFrame.reset_index
df = pd.concat([df, df_new]).drop_duplicates('date', keep='last').reset_index(drop=True)
print (df)
date A B
0 2019-01-01 1.0 a
1 2019-01-02 2.0 b
2 2019-01-03 3.5 c1
3 2019-01-04 4.0 d
4 2019-01-05 5.0 e
5 2019-01-06 6.0 f
推荐阅读
- angular - 角度 ngx-datatable 服务器端过滤
- react-native - 如何将用户名和密码保存在缓存中?反应式
- python - 为什么 (1) 是 int 以及它是如何工作的
- angular - 如何删除 ng-select 中的搜索框
- angular - 将 mixpannel 与 Angular 5 集成
- python - 在 Pandas 中读取带有波斯字符的 excel 文件
- biztalk - 将输出文件命名为 BizTalk 中元素的值
- reactjs - 提交值后如何重置antd datepicker?
- sql - SUM 舍入小数位 2
- c# - Wpf文本框验证控件模板触发文本值