【问题标题】:Appending dataframes onto excel将数据框附加到excel中
【发布时间】:2020-07-30 10:31:52
【问题描述】:

我已将 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,但我不太确定该怎么做

【问题讨论】:

  • 创建一个空数据框并使用for循环读取所有excel文件并将必填字段添加到空数据框

标签: python excel pandas dataframe


【解决方案1】:

您需要遍历每个 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

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

【讨论】:

    猜你喜欢
    • 2021-11-25
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    相关资源
    最近更新 更多