Skip to main content
 首页 » 编程设计

python之如何将数据框转换为以行和列作为 Pandas 键的字典

2025年05月04日11lvdongjie

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

 
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} 

请您参考如下方法:

在调用to_dict之前需要stack

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}