【发布时间】:2016-07-03 05:53:11
【问题描述】:
我在 pandas 中有一个数据框,我的目标是将数据框的每一行写入一个新的 json 文件。
我现在有点卡住了。我的直觉是遍历数据帧的行(使用 df.iterrows)并使用 json.dumps 转储文件,但无济于事。
有什么想法吗?
【问题讨论】:
我在 pandas 中有一个数据框,我的目标是将数据框的每一行写入一个新的 json 文件。
我现在有点卡住了。我的直觉是遍历数据帧的行(使用 df.iterrows)并使用 json.dumps 转储文件,但无济于事。
有什么想法吗?
【问题讨论】:
循环遍历索引是非常低效的。
更快的技术:
df['json'] = df.apply(lambda x: x.to_json(), axis=1)
【讨论】:
Pandas DataFrames 有一个 to_json 方法可以为你做这件事: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html
如果您希望每一行都在自己的文件中,您可以遍历索引(并使用索引来帮助命名它们):
for i in df.index:
df.loc[i].to_json("row{}.json".format(i))
【讨论】:
扩展@MrE 的答案,如果您希望将多列从单行转换为另一列,内容为 json 格式(而不是单独的 json 文件作为输出),我在使用时遇到了速度问题:
df['json'] = df.apply(lambda x: x.to_json(), axis=1)
使用这行代码,我在 175K 记录和 5 列的数据集上实现了显着的速度提升:
df['json'] = df.to_json(orient='records', lines=True).splitlines()
速度从 >1 分钟变为 350 毫秒。
【讨论】:
使用 apply,可以这样做
def writejson(row):
with open(row["filename"]+'.json', "w") as outfile:
json.dump(row["json"], outfile, indent=2)
in_df.apply(writejson, axis=1)
假设数据框有一个名为“文件名”的列,每个 json 行都有一个文件名。
【讨论】: