0

I need to add a TITLE just above header using Pandas script.

Sl_No  Departure    Arrival
 1      UK          India
 2      US          India        
 3      France      India
 4      New York    Singapore
 5      Tokyo       Singapore

I tried the below script but I'm not sure what changes I need to do in order to add TTITLE(top title)

    import os
    os.chdir("/dev/alb_shrd/alb/alb_prj/Files/albt/alt/scrpts")
    
    # Reading the csv file
    
    import pandas as pd
    print(pd.__file__)
    col_names=["Sl_No","Departure","Arrival"]
    
    df_new  = pd.read_csv("SourceFile.csv", quotechar='"',names=col_names, sep="|",skiprows=1, low_memory=False,error_bad_lines=False,header=None).dropna(axis=1, how="all")
    
header = pd.MultiIndex.from_product([["TOP TITLE"],list(df_new.columns)])
df_new.head()

pd.DataFrame(df_new.to_numpy(), None , columns = header).head()
   
    
    # Saving xlsx file
    
    file = f"SourceFile_{pd.Timestamp('now').strftime('%Y%m%d_%I%M')}.xlsx"
    df_new.to_excel(file, index=False)

Can anyone guide me how to add title at the top of the excel?

Thanks!

Jenifer
  • 387
  • 2
  • 11
  • 2
    Does this answer your question? [Inserting a row above pandas column headers to save a title name in the first cell of csv / excel file](https://stackoverflow.com/questions/66459258/inserting-a-row-above-pandas-column-headers-to-save-a-title-name-in-the-first-ce) – Michael Delgado Dec 18 '22 at 19:08
  • I tried adding these lines but it didn't work: header = pd.MultiIndex.from_product([["TOP TITLE"],list(df_new.columns)]) df_new.head() pd.DataFrame(df_new.to_numpy(), None , columns = header).head() – Jenifer Dec 19 '22 at 06:54
  • 1
    Can you try `df_new.columns = pd.MultiIndex.from_product([["TOP TITLE"],list(df_new.columns)])` instead `header = pd.MultiIndex.from_product([["TOP TITLE"],list(df_new.columns)]) df_new.head() pd.DataFrame(df_new.to_numpy(), None , columns = header).head()` ? – jezrael Dec 19 '22 at 06:56
  • Getting SyntaxError: invalid syntax. Looks like I'm missing something in the script – Jenifer Dec 19 '22 at 07:07

0 Answers0