基于另一个df列更新df列值

2024-10-16 17:15:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个dfqty和dfitem_info,我试图填充qty['item']中的NaN字段,其中:(我在这里引用SQL)

qty.ccy = item_info.ccy and qty.seller = item_info.seller 其中元组(ccy,seller)是两个df上的唯一标识符。你知道吗

DF qty
|  id | qty  |   item   | ccy | seller |
+-----+------+----------+-----+--------+
| 001 |  700 | CB04 box | USD | A1     |
| 002 |  500 | NaN      | AUS | A1     |
| 003 | 1500 | AB01 box | USD | B1     |



DF item_info
| sid | seller | ccy |   item   |
+-----+--------+-----+----------+
| AA1 | A1     | USD | CB04 box |
| AA2 | A2     | USD | CB01 Box |
| AA3 | A1     | AUS | AB01 box |

更新后的DFqty如下所示

DF qty
|  id | qty  |   item   | ccy | seller |
+-----+------+----------+-----+--------+
| 001 |  700 | CB04 box | USD | A1     |
| 002 |  500 | AB01 box | AUS | A1     |
| 003 | 1500 | AB01 box | USD | B1     |

Tags: infoboxiddfa1nanitemb1
2条回答

一种策略可能是在需要匹配的列上合并两个表,然后使用fillna。你知道吗

values = qty.merge(item_info, on=["ccy", "seller"], 
             how="left", suffixes=("_qty", "_info"))["item_info"]
qty["item"] = qty["item"].fillna(value=values)

以下方法可能有效。你知道吗

import pandas as pd
import numpy as np
dfg_item_info = item_info.groupby(["ccy", "seller"])
def fillna(x):
    if np.isnan(x["C"]):
        return (dfg_item_info
               .get_group((x["ccy"], x["seller"]))["item"]
               .values[0])
    else:
        return x["item"]

qty["item] = qty["item"].apply(fillna, axis=1)

相关问题 更多 >