Python 附加在 for 循环中生成的 Pandas 数据帧
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28669482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Appending pandas dataframes generated in a for loop
提问by El Confuso
I am accessing a series of Excel files in a for loop. I then read the data in the excel file to a pandas dataframe. I cant figure out how to append these dataframes together to then save the dataframe (now containing the data from all the files) as a new Excel file.
我正在 for 循环中访问一系列 Excel 文件。然后我将 excel 文件中的数据读取到 Pandas 数据框。我不知道如何将这些数据帧附加在一起,然后将数据帧(现在包含来自所有文件的数据)保存为一个新的 Excel 文件。
Here's what I tried:
这是我尝试过的:
for infile in glob.glob("*.xlsx"):
data = pandas.read_excel(infile)
appended_data = pandas.DataFrame.append(data) # requires at least two arguments
appended_data.to_excel("appended.xlsx")
Thanks!
谢谢!
采纳答案by biobirdman
Use pd.concatto merge a list of DataFrame into a single big DataFrame.
使用pd.concat以数据帧列表合并成一个大的数据帧。
appended_data = []
for infile in glob.glob("*.xlsx"):
data = pandas.read_excel(infile)
# store DataFrame in list
appended_data.append(data)
# see pd.concat documentation for more info
appended_data = pd.concat(appended_data)
# write DataFrame to an excel sheet
appended_data.to_excel('appended.xlsx')
回答by ye jiawei
you can try this.
你可以试试这个。
data_you_need=pd.DataFrame()
for infile in glob.glob("*.xlsx"):
data = pandas.read_excel(infile)
data_you_need=data_you_need.append(data,ignore_index=True)
I hope it can help.
我希望它能有所帮助。

