python - 使用索引作为键从数据框创建字典

标签 python pandas

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/

相关文章:

python - 压缩具有缺失值的数据帧行

python - 为什么 Mean() 在空 DataFrame 上有不同的行为?

python - 在某些列上交错 2 个数据帧

python - 使用 Python 对两列进行数字排序,但顺序不同

python - Win 64bit GetThreadContext 返回 zeroe'd out 寄存器,或 0x57 错误代码

python - 将文本字符串 K & M 转换为 10^3 & 10^6

python - 用两个for循环和python中的条件填充数据框

python - Pandas :合并数据框而不创建新列

javascript - Python + Selenium WebDriver,点击提交按钮

Python 解析 Minecraft 数据包