【问题标题】:Excel matrix to JSON via Pandas and Numpy.ndarray type通过 Pandas 和 Numpy.ndarray 类型将 Excel 矩阵转换为 JSON
【发布时间】:2017-07-29 07:48:32
【问题描述】:

我正在从 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

最终,我希望将其转换为字典列表,最后是 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()

矩阵很大,有很多零,所以我删除它们

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

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

【问题讨论】:

    标签: python excel numpy


    【解决方案1】:

    您可以坚持使用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},
    # ...
    

    【讨论】:

      猜你喜欢
      • 2022-10-07
      • 1970-01-01
      • 2011-06-13
      • 2011-10-18
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 2011-01-01
      • 2018-07-18
      相关资源
      最近更新 更多