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作为您想要的输出。使用堆栈的可能性很大。