我有 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)
我可以考虑找到两个数据帧之间的行差异,但当我考虑日期列时它不起作用。我可以听听你的建议吗?谢谢。
最佳答案
使用concat
并按 DataFrame.drop_duplicates
按 date
列删除重复项,最后通过DataFrame.reset_index
创建默认的uniqe索引值:
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
关于python - 附加 2 个带有行和列子集的 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55606347/