首页 > 解决方案 > 根据条件将df转换为嵌套字典

问题描述

我正在尝试以以下形式创建嵌套字典:

{
    "Principal Venue Product Code": {
        ["Spot month Lim", "Aggregate Lim"]: ["Venue Product Codes"]
    }
}

我正在使用默认的 dict 方法来转换熊猫数据框并具有以下代码(创建不相关的 df 代码):

ifeu_dict = defaultdict(dict)
for principal in df["Principal Venue Product Code"]:
    if principal not in ifeu_dict.keys():
        ifeu_dict[principal] = []


# adding IFEU limits
for (col, row) in df.iterrows():
    if (
        row.loc["Venue MIC"] == "IFEU"
        and len(ifeu_dict[row.loc["Principal Venue Product Code"]]) < 2
    ):
        if type(row.loc["Spot month single limit#"]) == int:
            ifeu_dict[row.loc["Principal Venue Product Code"]].append(
                row.loc["Spot month single limit#"]
            )
            ifeu_dict[row.loc["Principal Venue Product Code"]].append(
                row.loc["Other month limit#"]
            )
        if type(row.loc["Spot month single limit#"]) == str:
            try:
                int(str(row.loc["Spot month single limit#"])[0])
                ifeu_dict[row.loc["Principal Venue Product Code"]].append(
                    int(
                        str(row.loc["Spot month single limit#"])
                        .split()[0]
                        .replace(",", "")
                    )
                )
                ifeu_dict[row.loc["Principal Venue Product Code"]].append(
                    int(str(row.loc["Other month limit#"]).split()[0].replace(",", ""))
                )
            except ValueError:
                pass

除此之外,我的代码停止工作。我已将以下内容添加到上述循环中以尝试使其正常工作:

ifeu_dict[row.loc["Principal Venue Product Code"]][
    row.loc["Spot month single limit#"], row.loc["Other month limit#"]
].append(row.loc["Venue Product Codes"])

第一部分应该创建一个 {principal:[empty list]} 变量,而第二部分应该将场地产品代码添加到{bucket:list limit}如果他们在前一列中有存储桶。

谢谢你的时间,人们。

标签: pythonpython-3.xpandasdictionarynested

解决方案


推荐阅读