python - 从 pandas 数据帧创建字典,其中值是索引

标签 python pandas dictionary

我有一个像这样的 pandas 数据框:

A
a       
b
c
d

我正在尝试创建一个Python字典,如下所示:

df_dict = {'a':0, 'b':1, 'c':2, 'd':3}

我尝试过的:

df.reset_index(inplace=True)
df = {x : y for x in df['A'] for y in df['index']}

但是 df 长 75k,现在需要一段时间,甚至不确定这是否会产生我需要的结果。有没有一种简洁、快速的方法来实现这一目标?

最佳答案

dictziprange一起使用:

d = dict(zip(df['A'], range(len(df))))
print (d)
{'a': 0, 'b': 1, 'c': 2, 'd': 3}

关于python - 从 pandas 数据帧创建字典,其中值是索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64099176/

相关文章:

python - 为什么我不应该将项目文件放在 venv 文件夹中?

python - 名称错误 : name 'buffer' is not defined with Ant Based framework batch file

python - 返回多列 Pandas 对应的值

python - Pandas/Numpy 查找列标题和索引标题之间差异的方法

delphi - TDictionary.ContainsKey 返回 false,即使键存在

c++ - 在 C++ 中模拟 Python 字典时出现映射错误

python - 迭代卡住集与集合的内存差异

python - 创建新列导致 NaN

python - 主动份额措施的计算

json - TCL 字典转 JSON