如何在Python中按行追加Dataframe

如何在Python中按行追加Dataframe,python,pandas,dataframe,append,Python,Pandas,Dataframe,Append,我想(使用df.append())按行合并一些python数据帧。 下面报告的代码首先读取输入json\u dir\u路径中的所有json文件,它读取input\u fn=json\u数据[“accPreparedCSVFileName”],其中包含存储csv文件的完整路径,并在数据框df\u i中读取。当我尝试合并df\u output=df\u I.append(df\u output)时,我没有得到想要的结果 def __merge(self, json_dir_path):

我想(使用
df.append()
)按行合并一些python数据帧。 下面报告的代码首先读取输入
json\u dir\u路径中的所有json文件,它读取
input\u fn=json\u数据[“accPreparedCSVFileName”]
,其中包含存储csv文件的完整路径,并在数据框
df\u i
中读取。当我尝试合并
df\u output=df\u I.append(df\u 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个被合并。我做错了什么

任何帮助都将不胜感激

致以最良好的祝愿,
卡洛

您还可以在追加时设置
忽略_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在他的回答中所建议的,您可以加载数据帧列表并一次性连接它们。

我强烈建议您不要在循环中连接数据帧

将数据帧存储在一个列表中,然后在一次调用中连接列表中的项目,效率会更高。例如:

lst = []

for fn in input_fn:
    lst.append(pd.read_csv(fn))

df_output = pd.concat(lst, ignore_index=True)

谢谢你的回答。当然你同意我的代码也是正确的吗?是的,根据我所看到的,你的代码是正确的。你能在while循环中打印
json\u full\u name
,看看是否所有12个文件名都打印出来了吗?是的。是的。此外,我比较了您的方法和我的方法得到的行数,它们是相同的数。行数与单个文件中的行数之和不匹配?是的。这就是为什么我得出结论,我的代码也是正确的。请通过链接了解有关concat、追加和合并在pandas dataframe中工作的更多信息。