我有几个目录中的json数据文件,我想导入到Pandas中进行一些数据分析。json的格式取决于目录名中定义的类型。例如
dir1_typeA/
file1
file2
...
dir1_typeB/
file1
file2
...
dir2_typeB/
file1
...
dir2_typeA/
file1
file2
每个file
都包含一个复杂的嵌套json字符串,它将是DataFrame的一行。我将为每个TypeA和TypeB有两个数据帧。以后如果需要的话,我会附加它们。你知道吗
到目前为止,我已经有了所有需要的文件os.步行我试着通过
import os
from glob import glob
PATH = 'dir/filepath'
files = [y for x in os.walk(PATH) for y in glob(os.path.join(x[0], 'file*'))]
for file in files:
with open(issuefile, 'r') as f:
data = f.read()
data_json = json_normalize(json.loads(data))
type = ' '.join(issuefile.split('/')[3]
data_json['type'] = type
# append to data frame for typeA and typeB
if 'typeA' in type:
# append to typeA dataframe
else:
# append to typeB dataframe
另外还有一个问题,即目录中的文件可能有稍微不同的字段。例如,file1
可能还有几个字段file2
在dir1_typeA
中。所以,对于每种类型,我也需要在数据帧中适应这种动态特性。你知道吗
如何创建这两个数据帧?你知道吗
我认为在将这些文件读入pandas之前,应该首先将它们连接在一起,下面是如何在bash中实现(也可以在Python中实现):
然后可以使用
io.json.json_normalize
将其导入熊猫:相关问题 更多 >
编程相关推荐