[Python] Read excel with same column names with pandas

Discussão em 'Python' iniciado por Stack, Setembro 30, 2024.

  1. Stack

    Stack Membro Participativo

    I am trying to convert an excel to csv. The excel has the following headers -

    DATE,FIELD1,FEEDER BRANCH,50,100,200,500,1000,2000,FIELD2,50,100,200,500,1000,2000,FIELD3,50,100,200,500,1000,2000


    As seen, some columns are repeated. On loading the excel using pandas, it appends an index number to it. Eg. On repetition, 50 becomes 50.1, 100 becomes 100.1 ... and so on.

    How do I load the excel without this suffix. I want the col headers as is so that when writing as csv, the same is retained.

    Current code:

    def pandas_csv_from_excel(source):
    dir_and_file = source.split('/')
    filename = dir_and_file[len(dir_and_file) - 1].split('.')
    if not ((filename[1]).lower().startswith('xls')):
    return source

    csv_filename = f"{os.path.join(os.path.dirname(source), filename[0].lower())}.csv"
    location = os.path.dirname(source)
    df = pd.read_excel(source, index_col=None)
    df.to_csv(csv_filename, index=None)
    return csv_filename

    Continue reading...

Compartilhe esta Página