gpt4 book ai didi

python - 读取相同标题的 CSV 并在字典中分开

转载 作者:行者123 更新时间:2023-12-01 22:52:51 25 4
gpt4 key购买 nike

所以我在 API 请求中得到了一个 CSV,CSV 的格式是-

"id","loc_name","qty","loc_name","qty"
“NM001”、“HLR”、“10”、“KBD”、“20”
"NM003","KMG","15","SLD","25"

我想要一个这种格式的字典:{"NM001":{'HLR':'10', 'KBD':'20'}, "NM003":{"KMG": "15", "SLD": "25"}}

尝试过的代码-

field_names = next(csv.reader(csv_file,delimiter=","))
csv_file_handler = csv.DictReader(csv_file,delimiter=",",fieldnames=field_names)
对于 islice 中的每一行(csv_file_handler,1,无):
打印每一行

  • 这里的 csv_file 是我在响应中得到的文件。

result = {'id': 'NM001', 'loc_name': 'KBD', 'qty': '20'}
{'id': 'NM003', 'loc_name': 'SLD', 'qty': '25'}

csv.DictReader 中的问题在于它只会返回最后一个值,因为 header 相同。

最佳答案

我正在使用 pandas处理模块 csv文件。我可能会以这种方式解决这个问题(虽然这不是我认为的最佳方式,也不是 Pandas 的最佳方式。但是,嘿,它有效。

import pandas as pd
# read the csv as DataFrame, probably there is a way to get it from
# the API directly without saving to a file
# specify header as the first row
df = pd.read_csv("test.csv", header=0)
# empty dict
d = {}
# iterate over lines, I use this way, but I don't like it in fact
for i, key_id in enumerate(df["id"]):
# assign the values the way you want it
# however you need to specify it by names
# or indices
d[key_id.strip()] = {df.loc[i, "loc_name"]:df.loc[i, "qty"],
df.loc[i, "loc_name.1"]:df.loc[i, "qty.1"]}
print(d)
#{'"NM003"': {'SLD': 25, 'KMG': 15}, '"NM001"': {'HLR': 10, 'KBD': 20}}

如果您希望它与其他列一起使用(必须成对出现:key:val),那么您可以使用 df.ix[<row>,<col>]并首先遍历行(和以前一样),然后遍历列(添加 if 以仅添加非 nan 值):

for i, key_id in enumerate(df["id"]):
# create empty dict
d[key_id.strip()] = {}
# a less python more C-like syntax
# go through cols, skip the first and step is 2
for j in range(1, len(df.columns), 2):
# if there is some entry
if not pd.isnull(df.ix[i,j]):
d[key_id.strip()][df.ix[i, j]] = df.ix[i, j+1]

关于python - 读取相同标题的 CSV 并在字典中分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37274278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com