简体   繁体   English

将不同数据帧的列表保存到 json

[英]save a list of different Dataframes to json

I have different pandas dataframes, which I put in a list.我有不同的熊猫数据框,我把它们放在一个列表中。 I want to save this list in json (or any other format) which can be read by R.我想将此列表保存为 R 可以读取的 json(或任何其他格式)。

import pandas as pd

def create_df_predictions(extra_periods):
    """
    make a empty df for predictions  
    params: extra_periods = how many prediction in the future the user wants
    """
    df = pd.DataFrame({ 'model': ['a'], 'name_id': ['a'] })
    for col in range(1, extra_periods+1):
        name_col = 'forecast' + str(col)
        df[name_col] = 0

    return df

df1 = create_df_predictions(9) 
df2 = create_df_predictions(12)
list_df = [df1, df2]

The question is how to save list_df in a readable format for R?问题是如何将 list_df 保存为 R 的可读格式? Note that df1 and df2 are have a different amount of columns!请注意, df1 和 df2 的列数不同!

don't know panda DataFrames in detail, so maybe this won't work.不知道 Panda DataFrames 的细节,所以这可能行不通。 But in case it is kind of a traditional dict, you should be able to use the json module.但如果它是一种传统的 dict,你应该能够使用 json 模块。

df1 = create_df_predictions(9) 
df2 = create_df_predictions(12)
list_df = [df1, df2]

You can write it to a file, using json.dumps(list_df) , which will convert your list of dicts to a valid json representation.您可以使用json.dumps(list_df)将其写入文件,这会将您的json.dumps(list_df)列表转换为有效的 json 表示。

import json
with open("my_file", 'w') as outfile:
    outfile.write(json.dumps(list_df))

Edit: as commented by DaveR dataframes are't serializiable.编辑:正如 DaveR 所评论的那样,数据帧不可序列化。 You can convert them to a dict and then dump the list to json.您可以将它们转换为 dict,然后将列表转储为 json。

import json
with open("my_file", 'w') as outfile:
    outfile.write(json.dumps([df.to_dict() for df in list_df]))

Alternatively pd.DataFrame and pd.Series have a to_json() method, maybe have a look at those as well.或者 pd.DataFrame 和 pd.Series 有一个to_json()方法,也许也看看那些。

To export the list of DataFrames to a single json file, you should convert the list into a DataFrame and then use the to_json() function as shown below:要将 DataFrame 列表导出到单个 json 文件,您应该将列表转换为 DataFrame,然后使用to_json()函数,如下所示:

df_to_export = pd.DataFrame(list_df)
json_output = df_to_export.to_json()
with open("output.txt", 'w') as outfile:
    outfile.write(json_output)

This will export the full dataset to a single json string and export it to a file.这会将完整数据集导出为单个 json 字符串并将其导出到文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM