使用 Pandas 在标签中的单个 csv 表中添加多个 csv
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50522258/
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
Add multiple csv in a single csv sheet in tabs using Pandas
提问by steveJ
I have multiple csv files, lets say a.csv , b.csv . I want both a.csv and b.csv in a new c.csv . Both new csv should be in tabs inside as it is. I just want to add both csv in tabs . Is there any short way doing that in pandas. I have the below code with me but its not giving any output ,however its executing . Tried checking few posts in stackoverflow but somehow I did not got the wanted output. Please help me with some better solution.
我有多个 csv 文件,比如说 a.csv , b.csv 。我想要一个新的 c.csv 中的 a.csv 和 b.csv 。两个新的 csv 都应该在内部的标签中。我只想在 tabs 中添加两个 csv 。在Pandas中是否有任何捷径可以做到这一点。我有下面的代码,但它没有给出任何输出,但是它正在执行。尝试检查 stackoverflow 中的一些帖子,但不知何故我没有得到想要的输出。请帮助我一些更好的解决方案。
folders=next(os.walk('.'))[1]
for host in folders:
Path=os.path.join(os.getcwd(),host)
all_files = glob.glob(os.path.join(Path, "*.csv"))
df_from_each_file = (pd.read_csv(f) for f in all_files)
df = pd.concat(df_from_each_file, ignore_index=True)
df.to_csv('c.csv,' index=False)
回答by Martin Evans
A CSV file is really only ever a single sheet. An Excel xlsx
file though does support sheets. Pandas can be made to write directly to an Excel file using an ExcelWriter
. Something like the following should do what you need:
CSV 文件实际上只是一张纸。Excelxlsx
文件虽然支持工作表。可以使用 .pandas 直接将 Pandas 写入 Excel 文件ExcelWriter
。像下面这样的东西应该做你需要的:
import pandas as pd
import xlsxwriter
import glob
import os
writer = pd.ExcelWriter('multi_sheet.xlsx', engine='xlsxwriter')
folders = next(os.walk('.'))[1]
for host in folders:
Path = os.path.join(os.getcwd(), host)
for f in glob.glob(os.path.join(Path, "*.csv")):
print(f)
df = pd.read_csv(f)
df.to_excel(writer, sheet_name=os.path.basename(f)[:31])
writer.save()
For every CSV file that is found in your folders, a new Excel sheet will be created. The name of the sheet is the name of the CSV file, e.g. a.csv
would have the sheetname a
.
对于在文件夹中找到的每个 CSV 文件,都会创建一个新的 Excel 工作表。工作表的名称是 CSV 文件的名称,例如a.csv
将具有 sheetname a
。
Note: Excel has a restriction of 31 characters for a sheet name.
注意:Excel 的工作表名称限制为 31 个字符。