首页 > 解决方案 > 从只有唯一值的熊猫数据框中创建 python 字典

问题描述

我正在尝试将 pandas 数据框转换为只有每个键的唯一值的 python 字典。

我尝试使用 .to_dict('list') 但无法仅获取唯一值。

dictionary = dictionary.to_dict('list')


new_dict = {}

for key,value in dictionary.items():
    if value not in new_dict.items():
        new_dict[key] = value

标签: python-3.xpandas

解决方案


您可以使用:

dictionary = dictionary.drop_duplicates().to_dict('list')

您在转换为之前删除重复项dict


例子:

import pandas as pd
dictionary=pd.DataFrame(columns=['list'])
dictionary['list']=[1,2,3,9,4,5,6,7,7,4,3,7,9,'a','b','a','777']
dictionary = dictionary.drop_duplicates().to_dict('list')
print(dictionary)

输出:

{'list': [1, 2, 3, 9, 4, 5, 6, 7, 'a', 'b', '777']}

推荐阅读