熊猫-将Excel数据框转换为特定的词典格式

时间:2018-12-01 19:19:41

标签: python excel pandas dataframe formatting

我正在尝试将Excel文件转换为字典。我知道我可以将其转换为DataFrame并使用熊猫运行“ .to_dict()”。但是我需要特定的格式。这是Excel文件在下面格式化的方式


trade   curve   1m    2m     3m    4m

90210   mega    555   222    111   9991

606066  sdsdsd  4545  63232  3232  62626926

我需要字典看起来像这样。

{ trade : curve : [1m,2m,3m,4m ] }

从本质上讲,我希望每个交易都有一条曲线的值(可能有相同的交易,但曲线不同),并且该曲线具有一个数组作为其值。我了解我需要仔细阅读最初的“ to_dict”,但是我不确定如何

1 个答案:

答案 0 :(得分:0)

您可以通过如下迭代数据框来创建字典:

import pandas as pd

dataframe=pd.read_excel("data.xlsx",header=None)
dictionary={}
for index,row in dataframe.iterrows():
    dictionary[row[0]]={row[1]:[]}
    dictionary[row[0]][row[1]].append(row[2])
    dictionary[row[0]][row[1]].append(row[3])
    dictionary[row[0]][row[1]].append(row[4])
    dictionary[row[0]][row[1]].append(row[5])

print (dictionary)

上面的代码将提供以下输出:

{'trade': {'curve': ['1m', ' 2m', '3m', ' 4m']}, 90210: {'mega': [555, 222, 111, 9991]}, 606066: {'sdsdsd': [4545, 63232, 3232, 62626926]}}

我希望这是您所需要的。