【发布时间】:2022-01-01 10:27:37
【问题描述】:
我尝试读取多个 json 文件,用每个文件创建一个数据帧,然后将所有这些数据帧连接到一个数据帧中,但是程序只用它读取的最后一个文件创建一个数据帧而没有错误。所有 json 文件具有相同的结构。你知道我的代码要改什么吗?
代码如下:
import json
import pandas as pd
import os
df1=None
path = 'C:\\Users\\sotir\\Desktop\\machinedataset'
filenames = os.listdir(path)
for filename in sorted(filenames):
if filename.startswith("mpd.slice") and filename.endswith(".json"):
fullpath = os.sep.join((path, filename))
f = open(fullpath)
js = json.load(f)
f.close()
df= pd.json_normalize(js['playlists'], meta=['name', 'collaborative', 'pid', 'modified_at','num_tracks', 'num_albums',
'num_followers', 'num_edits', 'duration_ms', 'num_artists'],record_path= ['tracks'],
record_prefix='_')
if df1==None:
df1= df
else:
df1=pd.concat([df1,df])
我更新了代码,但出现了这个错误:
ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_20464/3545215146.py in <module>
16 'num_followers', 'num_edits', 'duration_ms', 'num_artists'],record_path= ['tracks'],
17 record_prefix='_')
---> 18 if df1==None:
19 df1= df
20 else:
~\anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
1440 @final
1441 def __nonzero__(self):
-> 1442 raise ValueError(
1443 f"The truth value of a {type(self).__name__} is ambiguous. "
1444 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
【问题讨论】:
-
你可能想做类似
df1=None; ...; df=pd. ...; if df1=None: df1=df; else: df1=pd.concat([df1,df]) -
我更新了代码但出现错误