且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在仅几列的行中替换值而不在Pandas中合并

更新时间:2023-09-23 09:37:58

IIUC,您可以使用 combine_first ,因为您不想合并。

IIUC, you can use combine_first as you don't want to merge.

df3 = df2.rename(columns={"Old_Date": "Date"}).set_index(["Date", "Daily_No"])[["Amount"]]\
    .combine_first(
    df1.set_index(['Date','Daily_No'])).dropna().reset_index()

print(df3)

         Date Daily_No   Amount   Name Type
0  30/01/2020      A12  10000.0    Bob    R
1  30/01/2020      A14   1000.0  Jacob    R
2  31/01/2020      B01     20.0   John    D






另一种方法是根据相互的列ffill& drop_duplicates只保留后面的值。


Another method would be to concat based on the mutual columns, ffill & drop_duplicates keeping only the later value.

df3 = pd.concat([df1,
       df2.rename(columns={'Old_Date': 'Date'})[['Date','Amount','Daily_No']]

      ],axis=0,sort=False)

df3.fillna(df3.groupby(['Daily_No','Date'],
            sort=False).ffill()).dropna().drop_duplicates(subset=['Daily_No','Date'],keep='last')

print(df3)


  Daily_No        Date   Name Type  Amount
1      A14  30/01/2020  Jacob    R    1000
2      B01  31/01/2020   John    D      20
0      A12  30/01/2020    Bob    R   10000