通过Pandas和Numpy.ndarraytypes将Excelmatrix转换为JSON

我正在从Excel文件中读取matrix。 matrix看起来像这样:

10100300 10100400 10100500 10100600 10100200 243 0 42 54 10100300 243 23 42 5443 10100400 243 110 42 543 10100500 243 0 432 543232342 10100600 243 440 42 544 10100700 243 0 42 54 

最终,我希望将其转换为一个字典列表,最后是一个JSON文件。

这看起来像这样:

 [{"Origin" : 10100200, "Destination" : 10100300, "flow" : 243}, {"Origin" : 10100400, "Destination" : 10100300, "flow" : 23}] 

首先,我使用pandas来读取这个数据: flows_data_df = pd.read_excel("file.xlsx")

转换为一个numpy数组: flow_data = flows_data_df.as_matrix()

matrix很大,有很多的零,所以我删除它们

clean_flow_data = flow_data[np.all(flow_data == 0, axis=1)]

在这一点上,我卡住了。 我如何从numpy.ndarraytypes到JSON

假设df是你从Excel中读入的原始dataframe,起源是dataframe的索引,目标是dataframe的列,你可以坚持使用具有to_dict方法的pandas

 (df.stack()[lambda x: x != 0].rename('flow').rename_axis(("Origin", "Destination")) .reset_index().to_dict("records")) #[{'Destination': '10100300', 'Origin': 10100200, 'flow': 243}, # {'Destination': '10100500', 'Origin': 10100200, 'flow': 42}, # {'Destination': '10100600', 'Origin': 10100200, 'flow': 54}, # {'Destination': '10100300', 'Origin': 10100300, 'flow': 243}, # ...