df.to_dict()
创建一个嵌套字典,其中标题构成键 {column:{index:value}}
。
有没有一种简单的方法可以创建字典,其中索引构成键,{index:column:value}}
?甚至 {index:(column,value)}
?
我可以创建字典然后反转它,但我想知道这是否可以一步完成。
最佳答案
在使用 df.to_dict
之前转置数据框。
df = pd.DataFrame({'a': [1, 3, 5], 'b': [2, 7, 5]})
print(df)
# a b
# 0 1 2
# 1 3 7
# 2 5 5
print(df.transpose().to_dict())
# {0: {'a': 1, 'b': 2},
# 1: {'a': 3, 'b': 7},
# 2: {'a': 5, 'b': 5}}
关于python - 使用索引作为键从数据框创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25451367/