Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从以索引为键的数据帧创建字典_Python_Pandas - Fatal编程技术网

Python 从以索引为键的数据帧创建字典

Python 从以索引为键的数据帧创建字典,python,pandas,Python,Pandas,df.to_dict()创建一个嵌套字典,其中头构成键,{column:{index:value} 有没有一种简单的方法可以创建一个索引构成键的字典,{index:column:value}?甚至{index:(列,值)} 我可以创建字典,然后将其反转,但我想知道这是否可以在一个步骤中完成。在使用df.to_dict之前转置数据帧 df = pd.DataFrame({'a': [1, 3, 5], 'b': [2, 7, 5]}) print(df) # a b # 0 1 2

df.to_dict()
创建一个嵌套字典,其中头构成键,
{column:{index:value}

有没有一种简单的方法可以创建一个索引构成键的字典,
{index:column:value}
?甚至
{index:(列,值)}


我可以创建字典,然后将其反转,但我想知道这是否可以在一个步骤中完成。

在使用
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}}

好吧,那太简单了。谢谢