【问题标题】:Issues with .JSON file conversion and CSV manipulation in PythonPython 中 .JSON 文件转换和 CSV 操作的问题
【发布时间】:2021-05-24 02:36:19
【问题描述】:

抱歉,帖子太长了!我有点 Python 文盲,所以请多多包涵:

我正在开展一个项目,该项目使用提取的 Fitbit 静息心率数据来比较一系列年份之间的心率值。 fitbit 数据导出为 .json 文件,我正在尝试将其转换为 .csv 以进行进一步分析。 我从 github 中提取了一个脚本,将 .json 文件转换为 .csv 格式的文件,但是在输入静息心率数据时我遇到了一些麻烦。

来自 .json 的示例行:

[{
"dateTime" : "09/30/16 00:00:00",
"value" : {
"date" : "09/30/16",
"value" : 76.83736383927637,
"error" : 2.737363838373737
}

将嵌套框架转换为列的 GitHub 代码部分:

# reading json into dataframes
resting_hr_df = get_json_to_df(file_list=resting_hr_file_list).reset_index()

# Heart rate contains a sub json that are explicitly converted into column
resting_hr_df['date'] = resting_hr_df['value'].transform(lambda x: make_new_df_value(x, 'date'))
resting_hr_df['value'] = resting_hr_df['value'].transform(lambda x: make_new_df_value(x, 'value'))
resting_hr_df['error'] = resting_hr_df['value'].transform(lambda x: make_new_df_value(x, 'error'))
resting_hr_df = resting_hr_df.drop(['value', 'index'], axis=1)

有两个名为“值”的变量,我认为这是导致问题的原因。

当使用 pandas 中的转换函数为嵌套数据框键分配变量名称时,第二个“值”值在 .csv 文件中存储为 0。 我应该如何存储这些值?

【问题讨论】:

    标签: python json pandas csv


    【解决方案1】:

    问题是这是一个嵌套的 json 文件。解决办法是用json加载json文件,然后用json_normalize加载到pandas中

    import json
    import pandas as pd
    
    with open('filename.json') as data_file:    
        data = json.load(data_file)  
    
    resting_hr_df = pd.json_normalize(data)
    resting_hr_df
    

    输出resting_hr_df:

    |    | dateTime          | value.date   |   value.value |   value.error |
    |---:|:------------------|:-------------|--------------:|--------------:|
    |  0 | 09/30/16 00:00:00 | 09/30/16     |       76.8374 |       2.73736 |
    

    【讨论】:

    • 绝对!并将数据框保存为 csv: resting_hr_df.to_csv("out.csv", sep=',', encoding='utf-8') .
    【解决方案2】:

    您可以使用 read_json 等默认的 pandas 函数轻松解决此方法。

    df = pd.read_json('abc.json', orient='index')
    data = df.to_csv(index=False)
    print(data)
    

    通过将json转换为csv文件可以轻松解决这个问题

    【讨论】:

      猜你喜欢
      • 2014-10-10
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 2015-01-13
      相关资源
      最近更新 更多