【问题标题】:Add new header to existing columns in excel using pandas使用 pandas 将新标题添加到 excel 中的现有列
【发布时间】:2018-12-07 16:57:42
【问题描述】:

我有一个如下所述的数据框。我想在现有数据框中添加新标头作为预期结果。谁能帮我做这件事。

一个:

   Name    Std   Tamil  Maths   Score  Result     Status
  Shankar   10    90     100     190     Pass      Good
  Shankar   10    50      20      70     Fail      Bad

我想在现有框架中添加主题和成绩作为标题

预期结果:

                 Subjects         Grade
  Name    std   Tamil  Maths    Score  Result       Status
 Shankar   10    90     100      190     Pass        Good
 Shankar    10    50      20       70     Fail        Bad

请任何人帮助我做预期的结果

最近得到如下:当我使用like [['']*1+['']*1+['Subjects'] * 2 + ['Grade'] * 2 + [''] *1,dfnew.columns]

我想删除自动创建的空行和第一列。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    set_index创建MultiIndex,列中所有不能设置为MultiIndex的列,然后分配嵌套列表:

    df = df.set_index(['Name','Std'])
    df.columns = [['Subjects'] * 2 + ['Grade'] * 2, df.columns]
    print (df)
                Subjects       Grade       
                   Tamil Maths Score Result
    Name    Std                            
    Shankar 10        90   100   190   Pass
    Kumar   10        50    20    70   Fail
    

    【讨论】:

    • 该问题的一个小改动。我将最后一列添加为 Status 。该列不在 Grade 下。请看那个。并且在这些更改之后也无法写入excel。我收到类似“”“NotImplementedError:使用MultiIndex列写入Excel并且没有索引('index'=False)尚未实现”“”的错误。当我使用 df.to_excel("DetailsReports.xlsx", index=False) – Python 团队 6 分钟前
    • @PythonTeam - 你能检查一下this 吗?
    • 对不起,我认为这与我的无关。看不懂:(
    • @PythonTeam - 使用df.to_excel("DetailsReports.xlsx", index=False, engine='xlsxwriter')
    • Name, Std 在使用上述答案时获得下一行。我的期望是 Name,Std 仅在同一行。 :( 而且它只显示一个名字为 Shankar。没有显示两次。我在预期结果中提到了我需要得到的结果。
    猜你喜欢
    • 2018-03-22
    • 2019-06-23
    • 2016-10-30
    • 2021-03-02
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    相关资源
    最近更新 更多