Lin*_*ang 1 python dictionary dataframe pandas
我有一个由以下数据和功能构造的数据框
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)
Run Code Online (Sandbox Code Playgroud)
我得到了这个矩阵:
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
Run Code Online (Sandbox Code Playgroud)
如何将此矩阵转换为以索引和列为键的字典?
我尝试了df.to_dict(),但是它仅使用列作为键。
它看起来应该像这样:
dict = {(barley, land): 0.3, (barley, labor): 0.1, ...(wheat, capital):0.2}
Run Code Online (Sandbox Code Playgroud)
And*_* L. 10
您需要stack
先致电to_dict
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}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
49 次 |
最近记录: |