python-3.x - 从只有唯一值的熊猫数据框中创建 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
解决方案
您可以使用:
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']}
推荐阅读
- python - 如何处理 biopython 翻译过程中的空白
- c# - 除了使用 -- 或 ++ 之类的运算符之外,您如何更改变量?
- python - 意外结果:pytest.raises with match parameter when asserting error
- css - 带阴影的发光盒效果
- javascript - 如何使用 jquery 将 bootstrap 4 导航项添加到活动的类中
- excel - sumif 如果条件是文本
- yacc - 编译基本 lex 和 yacc 计算器程序时出现多个错误
- swift - 如何 NSKeyedUnarchiver.unarchiveObject
- android - 如何在 SD 卡上存储文件(外部)
- python - 点击事件下载所有文件