python - 附加 2 个带有行和列子集的 pandas 数据框

标签 python 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 ,具体条件如下:

  1. 两个数据框中都有可用日期的任何行,我们在 df_new 中获取此类行

  2. 日期在 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_duplicatesdate 列删除重复项,最后通过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/

相关文章:

python - 在 ZipFile 中保留文件属性

python - Matplotlibrc 需要更新吗?

python - 将空白字符串替换为 nan

python - 导入错误 : No module named _backend_gdk

python - 对某些列执行 groupby.sum,对其他列执行 groupby.mean

python - 返回一个新列表的函数,其中包含原始列表中的值,这些值可被函数参数中的给定数字整除

python - 跨多列 DataFrame 的映射函数

python - 如何高效地实现这种差分运算呢?

python - 检查 Pandas DataFrame 索引是否为特定类型的正确方法 (DatetimeIndex)

python - 对 Pandas 中的分层数据进行子集化