如何在不同的Jupyter笔记本上获得不同的输出



我有两台计算机(个人和工作(:我正在从REST API调用相同的ndjson数据。这两台计算机都可以访问API,我使用相同的代码。

在我的个人电脑上,我使用以下代码来压平嵌套的ndjson文件。

def flatten_json(nested_json, exclude=['']):
"""Flatten json object with nested keys into a single level.
Args:
nested_json: A nested json object.
exclude: Keys to exclude from output.
Returns:
The flattened json object if successful, None otherwise.
"""
out = {}
def flatten(x, name='', exclude=exclude):
if type(x) is dict:
for a in x:
if a not in exclude: flatten(x[a], name + a + '_')
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + str(i) + '_')
i += 1
else:
out[name[:-1]] = x
flatten(nested_json)
return out

最后,我调用函数来压平ndjson文件

import pandas as pd 
from io import StringIO
import ndjson
import json
items = response.json(cls=ndjson.Decoder)
df = pd.json_normalize(items)
d = {}
for cols in df:
d[cols] = pd.DataFrame([flatten_json(x) for x in df[cols]])
print(d)

在我的个人电脑上,代码通过将返回DataFrames字典的ndjson数据文件扁平化来准确地工作。

然而,当我将这些代码复制并粘贴到我的工作电脑的Jupyter笔记本上时。ndjson文件仅被部分展开。这可能是版本问题吗?或者有人对解决这个问题有什么建议吗?

这两个环境之间可能存在不同的Python库或不同版本的Python库。

从Jupyter跟踪Python环境和依赖关系的一个好方法是使用Watermark插件https://github.com/rasbt/watermark其将列出版本。

最新更新