我有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
按date
列使用和删除重复项DataFrame.drop_duplicates
,最后按以下方法创建默认的uniqe索引值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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句