python - 如何在Python中按行追加Dataframe

标签 python pandas dataframe append

我想按行合并(使用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/

相关文章:

javascript - 解析 Javascript 日期

pandas - 如何使用 pandas 根据列 ID 将多个 csv 文件合并为 1 个文件

excel - 获取 Pandas 中具有特定值的单元格的行和列

python - tableview 在对 tablemodel 排序后未更新

python - 双向链表的长度实现,python

python - 在 groupby 或任何带参数的聚合函数中使用 np.average

python - 如何在 Pandas 饼图中显示值?

python - 如何合并数据框和填充值

Python:试图从 Pandas 的DataFrame中创建一个矩阵

python - 在 python 中的每个列表列表中 move 特定值(基于该值)