Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过Pandas和Numpy.ndarray类型将Excel矩阵转换为JSON_Python_Excel_Numpy - Fatal编程技术网

Python 通过Pandas和Numpy.ndarray类型将Excel矩阵转换为JSON

Python 通过Pandas和Numpy.ndarray类型将Excel矩阵转换为JSON,python,excel,numpy,Python,Excel,Numpy,我正在从excel文件中读取矩阵。矩阵如下所示: 10100300 10100400 10100500 10100600 10100200 243 0 42 54 10100300 243 23 42 5443 10100400 243 110 42 543 10100500

我正在从excel文件中读取矩阵。矩阵如下所示:

            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
最后,我希望将其转换为dict列表,最后转换为JSON文件

这看起来像:

[{"Origin" : 10100200,
"Destination" : 10100300,
"flow" : 243},
{"Origin" : 10100400,
"Destination" : 10100300,
"flow" : 23}]
首先,我用熊猫来读这篇文章:
flows\u data\u df=pd.read\u excel(“file.xlsx”)

转换为numpy数组:
flow\u data=flows\u data\u df.as\u matrix()

矩阵很大,有很多零,所以我去掉了它们

clean\u flow\u data=flow\u data[np.all(flow\u data==0,axis=1)]


在这一点上,我被卡住了。如何从
numpy.ndarray
类型转换为
JSON

您可以坚持使用
pandas
方法,该方法具有
to_dict
方法,假设
df
是从excel读取的原始数据框,源是数据框的索引,目标是数据框的列:

(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},
# ...