我有不同的 Pandas 数据框,我把它们放在一个列表中。 我想用 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]
问题是如何以 R 可读的格式保存 list_df?请注意,df1 和 df2 的列数不同!
请您参考如下方法:
不详细了解 panda DataFrames,所以这可能行不通。但如果它是一种传统的字典,您应该能够使用 json 模块。
df1 = create_df_predictions(9)
df2 = create_df_predictions(12)
list_df = [df1, df2]
您可以使用 json.dumps(list_df) 将其写入文件,这会将您的字典列表转换为有效的 json 表示形式。
import json
with open("my_file", 'w') as outfile:
outfile.write(json.dumps(list_df))
编辑:正如 DaveR 所说,数据帧不可序列化。您可以将它们转换为字典,然后将列表转储为 json。
import json
with open("my_file", 'w') as outfile:
outfile.write(json.dumps([df.to_dict() for df in list_df]))
或者 pd.DataFrame 和 pd.Series 有一个 to_json() 方法,或许也可以看看那些。
