[Python] Cleaning column names in pandas

Discussão em 'Python' iniciado por Stack, Abril 28, 2025.

  1. Stack

    Stack Membro Participativo

    I have a Dataframe I receive from a crawler that I am importing into a database for long-term storage.

    The problem I am running into is a large amount of the various dataframes have uppercase and whitespace.

    I have a fix for it but I was wondering if it can be done any cleaner than this:

    def clean_columns(dataframe):
    for column in dataframe:
    dataframe.rename(columns = {column : column.lower().replace(" ", "_")},
    inplace = 1)
    return dataframe


    print(dataframe.columns)

    Index(['Daily Foo', 'Weekly Bar'])

    dataframe = clean_columns(dataframe)
    print(dataframe.columns)


    Index(['daily_foo', 'weekly_bar'])

    Continue reading...

Compartilhe esta Página