首页 > 解决方案 > 将数据框附加到excel

问题描述

我已将 excel 读入一个数据框,如下所示:

df =

Item   Questions     Answer
1      First name    Alex
1.1    Age           43
1.2    Nationality   English
etc....

我有许多类似的 excel 文件,例如这些我打算读入数据帧的文件,但是我想将所有这些文件整理到一个单独的 excel 中。我不想包括所有列,所以对于上面的数据框,我希望它在添加到单独的 excel 后看起来像下面这样:

First Name   Age   Nationality
Alex         43    English

另外,我如何将其他类似的数据框添加到这个单独的 excel 中,我认为它会使用 append,但我不太确定该怎么做

标签: pythonexcelpandasdataframe

解决方案


您需要遍历每个 excel 表(读入它们)并首先旋转或转置数据框以获得所需的列格式(有多种方法可以做到这一点),然后将其连接到单独的单个数据框:

total_dataframe = pd.DataFrame() #initialize empty table

for file in my_excel_files:
    df = pd.read_csv(file) 
    df = pd.DataFrame(df.values.T) #transpose the table
    headers = df.iloc[0] #Make first row the column headers
    new_df = pd.DataFrame(df.values[1:], columns=headers)
    total_dataframe = pd.concat([total_dataframe, new_df]) #append to final table

当然有更优雅的方法可以做到这一点,但我认为这很清楚地打破了这个过程。


推荐阅读