在Python字典中将特定列中的项目作为键时出现关键错误。

huangapple go评论60阅读模式
英文:

Key error when making items in a particular column as keys in python dictionary

问题

以下是您要翻译的内容:

"Name, Value [abc/g]
abc_123_def.77, 4.954172

我想将“Name”中的内容作为键,同时这些键的值应该是从0开始递增的数字。以下是我尝试实现此目标的代码:

My_dict = {}
count=0

csvfile = pd.read_csv(my_txt)
for idx, column in csvfile.iterrows():
My_dict[column['Name']].append(count)
count = count+1

然而,我收到以下错误消息:

KeyError: 'abc_123_def.77'

我的目标是生成如下所示的字典:

{"abc_123_def.77": 1, "abc_123_def.67": 2}

对我有任何见解都将不胜感激。提前感谢您。"

英文:

Below is a sample of my csv file (I have only included the first row but I have hundreds of rows):

Name, Value [abc/g]
abc_123_def.77, 4.954172

I want to make the contents of "Name" as keys meanwhile the value for this keys should be increasing numbers starting from 0. Here is the code I have written in attempt to achieve this:

My_dict = {}
count=0

csvfile = pd.read_csv(my_txt)
for idx, column in csvfile.iterrows():
        My_dict[column['Name']].append(count)
        count = count+1

However, I am getting the following error:

KeyError: 'abc_123_def.77'

My goal is to generate a dictionary like the following:

{"abc_123_def.77": 1, "abc_123_def.67": 2}

Any insights for me is appreciated. Thank you in advance

答案1

得分: 0

你正在错误地插入数据。
尝试

My_dict[column['Name']] = count
英文:

You are instering the data wrong.
try

My_dict[column['Name']] = count

huangapple
  • 本文由 发表于 2023年5月14日 22:09:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76247897.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定