问题描述
问题是: 我想从多个不同的excell(.xlsx)填充,特定的ccolumns中提取并将所有这些保存在不同的excell-Sheet中。 我可以在终端中使用DataFrame,但只能将最后加载的.xlsx保存在excell工作表中。 我做错了什么?如何解决这个问题? 熊猫对这个常见问题有一个简单的命令吗? 我尝试了许多来自“ stackoverflow”的解决方案,但我找不到正确的方法。
import pandas as pd
import numpy as np
df_col=pd.DataFrame()
print(df_col)
i=0
while i<len(files):
# Import the excel file and call it xls_file
xls_file = pd.ExcelFile(files[i])
# Load the xls file's Sheet1 as a dataframe
df = xls_file.parse()
need_df = pd.read_excel(files[i],usecols=list_col_pros)
########################################################
# Create a Pandas Excel writer using XlsxWriter as the engine.
df_col.append(need_df)
##########################################################
# Returns column with label col as Series
print(need_df)
i=i+1
##########################
print(df_col)
writer = pd.ExcelWriter('all_pros.xlsx',engine='xlsxwriter')
# Write each dataframe to a different worksheet.
df_col.to_excel(writer,sheet_name='Sheet')
# Close the Pandas Excel writer and output the Excel file.
writer.save()
解决方法
所以这可以工作。我用标题为“开始位置”的列B制作了一些虚拟文件 但我认为您应该可以轻松地将其更改为文件名/列。
import pandas as pd
import numpy as np
df_col=pd.DataFrame()
print(df_col)
files = ["1.xlsx","2.xlsx","3.xlsx"]
i=0
while i<len(files):
# Import the excel file and call it xls_file
# xls_file = pd.ExcelFile(files[i])
# Load the xls file's Sheet1 as a dataframe
# df = xls_file.parse()
need_df = pd.read_excel(files[i],usecols="B")
########################################################
# Create a Pandas Excel writer using XlsxWriter as the engine.
df_col[files[i]] = need_df['First Position'].values
##########################################################
# Returns column with label col as Series
print(need_df)
i=i+1
##########################
print(df_col)
writer = pd.ExcelWriter('all_pros.xlsx',engine='xlsxwriter')
# Write each dataframe to a different worksheet.
df_col.to_excel(writer,sheet_name='Sheet')
# Close the Pandas Excel writer and output the Excel file.
writer.save()