如何在Python Pandas中以追加模式将DataFrame导出为JSON文件?

5

我有一个现有的json文件,格式为字典列表。

$cat output.json
[{'a':1, 'b':2}, {'a':2, 'b':3}]

我有一个数据框

df = pd.DataFrame({'a':pd.Series([1,2], index=list('CD')), \
              "b":pd.Series([3,4], index=list('CD')})
我希望使用 to_json 将“df”保存并追加到文件 output.json 中:
df.to_json('output.json', orient='records')  #  mode='a' not available for to_json

* to_csv 有 append mode='a',但是 to_json 真的没有。

期望生成的 output.json 文件将会是:

    [{'a':1, 'b':2}, {'a':2, 'b':3}, {'a':1, 'b':3}, {'a':2, 'b':4}]
现有的输出文件output.json可能非常大(比如说以太字节),是否有可能在不加载文件的情况下追加新的数据框结果?
5个回答

3
你可以这样做。它会将每个记录/行作为json写入新行。
f = open(outfile_path, mode="a")

for chunk_df in data:
    f.write(chunk_df.to_json(orient="records", lines=True))

f.close()

1
不,你不能通过使用pandas或json模块把数据附加到JSON文件中而不重写整个文件。你也许可以通过以a模式打开文件并寻找正确的位置插入数据来"手动"修改文件。但我不建议这样做。如果你的文件大小超过了内存容量,最好使用其他文件格式。此外,这个答案也可能会有帮助。它不会创建有效的JSON文件(每行是一个JSON字符串),但它的目标与你很相似。

0
也许你需要考虑使用 orient='records' 参数:
def to_json_append(df,file):
    '''
    Load the file with
    pd.read_json(file,orient='records',lines=True)
    '''
    df.to_json('tmp.json',orient='records',lines=True)
    #append
    f=open('tmp.json','r')
    k=f.read()
    f.close()
    f=open(file,'a')
    f.write('\n') #Prepare next data entry
    f.write(k)
    f.close()

df=pd.read_json('output.json')
#Save again as lines
df.to_json('output.json',orient='records',lines=True)
#new data
df = pd.DataFrame({'a':pd.Series([1,2], index=list('CD')), \
              "b":pd.Series([3,4], index=list('CD')})
#append:
to_json_append(df,'output.json')

加载完整数据

pd.read_json('output.json',orient='records',lines=True)

0

应用场景,使用小内存将大量数据写入JSON文件:

假设我们有1,000个数据帧,每个数据帧类似于100万行的json。每个数据帧需要100MB,总文件大小将为1000 * 100MB = 100GB。

解决方案:

  1. 使用缓冲区存储每个数据帧的内容
  2. 使用Pandas将其转储为文本
  3. 使用附加模式将文本写入文件末尾
import io
import pandas as pd
from pathlib_mate import Path

n_lines_per_df = 10
n_df = 3
columns = ["id", "value"]
value = "alice@example.com"
f = Path(__file__).change(new_basename="big-json-file.json")
if not f.exists():
    for nth_df in range(n_df):
        data = list()
        for nth_line in range(nth_df * n_lines_per_df, (nth_df + 1) * n_lines_per_df):
            data.append((nth_line, value))
        df = pd.DataFrame(data, columns=columns)
        buffer = io.StringIO()
        df.to_json(
            buffer,
            orient="records",
            lines=True,
        )
        with open(f.abspath, "a") as file:
            file.write(buffer.getvalue())

0

我只是使用内置的pandas.DataFrame方法解决了它。在处理大型数据框时,您需要考虑性能(有方法来处理它)。 代码:

if os.path.isfile(dir_to_json_file):
    # if exist open read it
    df_read = pd.read_json(dir_to_json_file, orient='index')
    # add data that you want to save
    df_read = pd.concat([df_read, df_to_append], ignore_index=True)
    # in case of adding to much unnecessery data (if you need)
    df_read.drop_duplicates(inplace=True)

    # save it to json file in AppData.bin
    df_read.to_json(dir_to_json_file, orient='index')
else:
    df_to_append.to_json(dir_to_json_file, orient='index')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,