簡體   English   中英

如何根據條件從另一個 Dataframe 更新 Dataframe 值

[英]How to update a Dataframe values from an another Dataframe based on condition

我正在嘗試更新 Dataframe 中基於另一個 Dataframe “數量”列的“數量”列,僅為特定行(根據特定類型)。

這是我的示例數據框:

df = pd.DataFrame({'op': ['A', 'A', 'A', 'B', 'C'], 'type': ['X', 'Y', 'Z', 'X', 'Z'], 'qty': [3, 1, 8, 0, 4]})
df_xy = pd.DataFrame({'op': ['A', 'B', 'C'], 'qty': [10, 20, 30]})
print(df)
print(df_xy)

  op type  qty
0  A    X    3
1  A    Y    1
2  A    Z    8
3  B    X    0
4  C    Z    4

  op  qty
0  A   10
1  B   20
2  C   30

我嘗試使用 loc function 選擇相關行並根據我的參考列“op”與其他 Dataframe 進行比較但沒有成功

# Select df rows where "type" is in "types" and set "qty" according to "qty" from df_xy
types = ['X', 'Y']
df.loc[df['type'].isin(types), 'qty'] = df_xy.loc[df_xy['op'] == df['op'], 'qty']
print(df)

我想要一個 Dataframe 是這樣的:

  op type  qty
0  A    X    10
1  A    Y    10
2  A    Z    8
3  B    X    20
4  C    Z    4

但是我有一個錯誤,指出我無法比較未以相同方式標記的系列對象

ValueError: Can only compare identically-labeled Series objects

任何幫助深表感謝! 提前致謝!

僅對兩側的過濾行使用Series.map以避免處理不匹配的行,這里是Z行:

types = ['X', 'Y']
mask = df['type'].isin(types)
df.loc[mask, 'qty'] = df.loc[mask, 'op'].map(df_xy.set_index('op')['qty'])
print (df)
  op type  qty
0  A    X   10
1  A    Y   10
2  A    Z    8
3  B    X   20
4  C    Z    4

您可以結合locmerge來對齊您的 2 系列:

df.loc[df['type'].isin(types), 'qty'] = df[['op']].merge(df_xy, on='op')['qty']

output:

  op type  qty
0  A    X   10
1  A    Y   10
2  A    Z    8
3  B    X   20
4  C    Z    4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM