如何使用Python的pandas将每个Excel表格中的第一列和最后一列组合成新的Excel表格?

2024-04-25 00:09:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个excel文件,它由多张纸(~100张纸)和8列组成。我试图把我的第一列“日期”和最后一列“预测”合并到新的excel文件中。因此,我的新excel文件应该将每个工作表的“日期”和“预测”列合并到一个工作表中,并具有多个预测列。为此,我的思想过程是首先读取文件,而不是使用pandas concat()连接“prediction”列。但是当我这么做的时候,python生成了很多NaN's。我很好奇,如果我们能以更好的方式实现这个目标。你知道吗

**Sheet 1:**
Date    col1    Col2 .....   Prediction1
01/01     9         5               5
02/01     3         7               5

**Sheet2**
Date    col1    Col2 .....   Prediction2
01/01     9         5               4
02/01     3         7               6

注意:我是python新手,请提供代码解释。你知道吗

代码:

  #Reading file
  df=pd.read_excel('myexcel.xlsx")

  #Combining files
  excel_combine=pd.concat(df[frame] for frame in df.keys())

预期输出:

    Date       Prediction1         Prediction2
    01/01            5               4
    02/01            5                6

Tags: 文件代码pandasdfdate过程excelframe
1条回答
网友
1楼 · 发布于 2024-04-25 00:09:26

这将为您提供一个数据帧,其中所有预测列都被整齐地重命名。 串联并不总是给你最好的结果。或许可以尝试合并。 也可以在这里查看关于这个主题的熊猫文档:https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html

import xlrd
import pandas

# Open the workbook
bk = xlrd.open_workbook('input_file_name')

# set counter to zero
n = 0

# loop through the sheet names
for i in bk.sheet_names():
   # read one sheet into a df at a time
   temp_df = pd.read_excel(file_name, sheet_name = i)
   # set a new column name according to which sheet the prediction came from
   new_col_name = 'pred_' + i
   # rename the prediction column
   temp_df.rename(columns = {'predition' : new_col_name}, inplace = True)

   n += 1 # add one to counter each time a new sheet is processed

   if n == 1:
      # if this is the first loop a dtaframe called df is created
      df = temp_df.copy()

   else:
      # if it is not the first loop merge the temp_df with the df table
      df = df.merge(temp_df,
                    on = 'date',
                    how = 'left') # assuming you do have equal time series for all predictions I set a left join, otherwise a outer join may be better - look this up if you don't know it

# check df if everything is there
print df.info()
print df.head()
print df.describe()

# write to excel
df.to_excel('your_file_name', index = False)

相关问题 更多 >