我想按行合并(使用df.append()
)一些Python数据帧。
下面报告的代码首先读取输入 json_dir_path
中的所有 json 文件,它读取包含 csv 所在的完整路径的 input_fn = json_data["accPreparedCSVFileName"]
文件在数据帧df_i
中存储和读取。当我尝试合并 df_output = df_i.append(df_output) 时,我没有获得所需的结果。
def __merge(self, json_dir_path):
if os.path.exists(json_dir_path):
filelist = [f for f in os.listdir( json_dir_path )]
df_output = pd.DataFrame()
for json_fn in filelist:
json_full_name = os.path.join( json_dir_path, json_fn )
# print("[TrainficationWorkflow::__merge] We are merging the json file ", json_full_name)
if os.path.exists(json_full_name):
with open(json_full_name, 'r') as in_json_file:
json_data = json.load(in_json_file)
input_fn = json_data["accPreparedCSVFileName"]
df_i = pd.read_csv(input_fn)
df_output = df_i.append(df_output)
return df_output
else:
return pd.DataFrame(data=[], columns=self.DATA_FORMAT)
我只合并了 12 个文件中的 2 个。我做错了什么?
任何帮助将不胜感激。
最诚挚的问候, 卡洛
最佳答案
您还可以在 append 时设置ignore_index=True
。
df_output = df_i.append(df_output, ignore_index=True)
您还可以连接数据帧:
df_output = pd.concat((df_output, df_i), axis=0, ignore_index=True)
正如 @jpp 在他的回答中所建议的,您可以加载数据帧列表并一次性连接它们。
关于python - 如何在Python中按行追加Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50161081/