Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.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_Dataframe_Dictionary - Fatal编程技术网

Python 如何将数据帧转换为以行和列作为键的字典?

Python 如何将数据帧转换为以行和列作为键的字典?,python,pandas,dataframe,dictionary,Python,Pandas,Dataframe,Dictionary,我有一个由以下数据和函数构造的数据框架 model.Crops = ["barley", "rapeseed", "wheat"] model.FixedInputs = ["land", "labor", "capital"] Beta = [[0.3, 0.1, 0.3],\ [0.2, 0.1, 0.2],\ [0.3, 0.1, 0.2]] pd.DataFrame(data=Beta_F_Data, index=model.Crops, colum

我有一个由以下数据和函数构造的数据框架


model.Crops = ["barley", "rapeseed", "wheat"]
model.FixedInputs = ["land", "labor", "capital"]
Beta =  [[0.3, 0.1, 0.3],\
        [0.2, 0.1, 0.2],\
        [0.3, 0.1, 0.2]]

pd.DataFrame(data=Beta_F_Data, index=model.Crops, columns=model.FixedInputs)

我得到了这个矩阵:

FixedInputs  land  labor  capital
Crops                            
barley        0.3    0.1      0.3
rapeseed      0.2    0.1      0.2
wheat         0.3    0.1      0.2

如何将此矩阵转换为索引和列作为键的字典

我尝试了df.to_dict(),但它只使用列作为键

应该是这样的:

dict = {(barley, land): 0.3, (barley, labor): 0.1, ...(wheat, capital):0.2}

在调用
命令之前,您需要
堆栈

df.stack().to_dict()

Out[389]:
{('barley', 'land'): 0.3,
 ('barley', 'labor'): 0.1,
 ('barley', 'capital'): 0.3,
 ('rapeseed', 'land'): 0.2,
 ('rapeseed', 'labor'): 0.1,
 ('rapeseed', 'capital'): 0.2,
 ('wheat', 'land'): 0.3,
 ('wheat', 'labor'): 0.1,
 ('wheat', 'capital'): 0.2}

在调用
命令之前,您需要
堆栈

df.stack().to_dict()

Out[389]:
{('barley', 'land'): 0.3,
 ('barley', 'labor'): 0.1,
 ('barley', 'capital'): 0.3,
 ('rapeseed', 'land'): 0.2,
 ('rapeseed', 'labor'): 0.1,
 ('rapeseed', 'capital'): 0.2,
 ('wheat', 'land'): 0.3,
 ('wheat', 'labor'): 0.1,
 ('wheat', 'capital'): 0.2}

很好地使用了
堆栈
!为什么stack在这里如此神奇?堆栈还能做什么?堆栈的主要用途是透视数据帧。无论何时,只要您认为需要以某种方式透视
df
stack
可能是一个选项<代码>堆栈将创建多索引系列或数据帧。多索引通过
到dict
转换为
元组
键。我使用
stack
的这个特性来创建dict作为您想要的输出。使用
stack
的可能性很大。这里很好地使用了
stack
!为什么stack在这里如此神奇?堆栈还能做什么?堆栈的主要用途是透视数据帧。无论何时,只要您认为需要以某种方式透视
df
stack
可能是一个选项<代码>堆栈将创建多索引系列或数据帧。多索引通过
到dict
转换为
元组
键。我使用
stack
的这个特性来创建dict作为您想要的输出。使用
堆栈的可能性很大。