我有兩個資料框。第二個資料幀包含第一個資料幀中要更新的值。df1:
data=[[1,"potential"],[2,"lost"],[3,"at risk"],[4,"promising"]]
df=pd.DataFrame(data,columns=['id','class'])
id class
1 potential
2 lost
3 at risk
4 promising
df2:
data2=[[2,"new"],[4,"loyal"]]
df2=pd.DataFrame(data2,columns=['id','class'])
id class
2 new
4 loyal
預期輸出:
data3=[[1,"potential"],[2,"new"],[3,"at risk"],[4,"loyal"]]
df3=pd.DataFrame(data3,columns=['id','class'])
id class
1 potential
2 new
3 at risk
4 loyal
下面的代碼似乎有效,但我相信有一個更有效的解決方案。
final=df.append([df2])
final = final.drop_duplicates(subset='id', keep="last")
另外:有沒有辦法讓我把以前的值寫在一個新的列中?像這樣:
id class prev_class modified date
1 potential nan nan
2 new lost 2022.xx.xx
3 at risk nan nan
4 loyal promising 2022.xx.xx
uj5u.com熱心網友回復:
您的解決方案很好,這里可以替代concat并添加DataFrame.sort_values:
df = (pd.concat([df, df2])
.drop_duplicates(subset='id', keep="last")
.sort_values('id', ignore_index=True))
print (df)
id class
0 1 potential
1 2 new
2 3 at risk
3 4 loyal
如果需要添加以前的class值和今天,解決方案是更改:
df3 = pd.concat([df, df2])
mask = df3['id'].duplicated(keep='last')
df31 = df3[mask]
df32 = df3[~mask]
df3 = (df32.merge(df31, on='id', how='left', suffixes=('','_prev'))
.sort_values('id', ignore_index=True))
df3.loc[df3['class_prev'].notna(), 'modified date'] = pd.to_datetime('now').normalize()
print (df3)
id class class_prev modified date
0 1 potential NaN NaT
1 2 new lost 2022-03-31
2 3 at risk NaN NaT
3 4 loyal promising 2022-03-31
uj5u.com熱心網友回復:
我們可以用DataFrame.update
df = df.set_index('id')
df.update(df2.set_index('id'))
df = df.reset_index()
結果
print(df)
id class
0 1 potential
1 2 new
2 3 at risk
3 4 loyal
uj5u.com熱心網友回復:
您可以通過將它們設定為索引來沿您的 id 進行操作,并用于combine_first執行此操作。然后分配 yourreprev_class非常簡單,因為您已經正確使用了Index!
df = df.set_index('id')
df2 = df2.set_index('id')
out = (
df2.combine_first(df)
.assign(
prev_class=df2["class"],
modified=lambda d:
d["prev_class"].where(
d["prev_class"].isna(), pd.Timestamp.now()
)
)
)
print(out)
class prev_class modified
id
1 potential NaN NaN
2 new new 2022-03-31 06:51:20.832668
3 at risk NaN NaN
4 loyal loyal 2022-03-31 06:51:20.832668
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453452.html
