python - 根据条件将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}
如果他们在前一列中有存储桶。
谢谢你的时间,人们。
解决方案
推荐阅读
- json - 在 Delphi 中用斜杠解析 JSON
- python - Pandas 通过与另一个 Dataframe 的比较来替换列的值
- terraform - 如何在外部数据查询中使用模块输出变量
- python-3.x - Pandas Dataframe Query - 每行最高值的位置
- html - 如何将Angular Material卡片显示为列而不是行
- javascript - 有没有办法可以将数据从注册表单发送到另一个 HTML 页面?
- firebase - 仅在发布模式下,具有 Firebase 的 Flutter 应用程序才会崩溃
- apache-kafka - 通过 Kafka Consumer 消费消息时出错
- javascript - JavaScript修改innerHTML后从PHP中的HTML标签获取文本
- pandas - 向熊猫数据框添加额外的日期行