如何为 python 中的每个值分配数字

How to assign number to each value in python

我对 python 和数据科学比较陌生,我正在处理一个类似于以下内容的 CSV 文件:

value1, value2
value3
value4...

事实是,我想为 csv 文件中的每个值分配一个唯一编号,以便唯一编号充当键,CSV 中的项目充当字典中的值。

我尝试使用 pandas,但如果可能的话,我想知道如何在不使用任何库的情况下解决这个问题。

所需的输出应该是这样的:

{
"value1": 1,
"value2": 2,
"value3": 3,
.
.
.
and so on..
}

正要谈论 pandas 之前我看到你想在香草 Python 中做到这一点。我个人会用 pandas 来做,但是给你:

您可以从文件中读入行,用分隔符 (',') 将它们分开,然后得到您的单词标记。

master_dict = {}
counter = 1
with open("your_csv.csv", "r") as f:
    for line in f:
        words = line.split(',') # you may or may not want to add a call to .strip() as well
        for word in words:
            master_dict[counter] = word
            counter += 1