DataFrameとCOALESCE

# df1(id, col)
# df2(id, col)
やりたきこと:df1をdf2で更新

— SQL
SELECT
    COALESCE(b.id, a.id) AS id
  , COALESCE(b.col, a.col) AS col
FROM df1 a
FULL OUTER JOIN df2 b
ON a.id = b.id

# Python
df = pd.merge(df1, df2, on=’id’, how=’outer’, suffixes=[‘_old’, ”])
# 方法1
df[‘col’] = df[‘col’].combine_first(df[‘col_old’])
df.drop(columns=[‘col_old’], inplace=True)
# 方法2
df[‘col’] = df[‘col’].fillna(df[‘col_old’])
df.drop(columns=[‘col_old’], inplace=True)

コメント

タイトルとURLをコピーしました