1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Add a cell above the first column in Pandas dataframe

Discussão em 'Python' iniciado por Stack, Setembro 28, 2024 às 06:52.

  1. Stack

    Stack Membro Participativo

    I have a dataframe, say df:

    import pandas as pd

    # create a dataframe
    df = pd.DataFrame({
    "Name": ["Alice", "Bob", "Charlie"],
    "Age": [25, 30, 35],
    "City": ["New York", "Los Angeles", "Chicago"]
    })
    df

    Name Age City
    Alice 25 New York
    Bob 30 Los Angeles
    Charlie 35 Chicago

    I want to add a cell on top of the first column (Name) with cell color - Yellow, something like - [​IMG]

    I want Name, Age and City to remain as columns.

    I have tried it, but the approach isn't good, but I know there might be some other better way. My code below:

    import pandas as pd

    # create a dataframe
    df = pd.DataFrame({
    "Name": ["Alice", "Bob", "Charlie"],
    "Age": [25, 30, 35],
    "City": ["New York", "Los Angeles", "Chicago"]
    })
    # change the column name for temporary basis
    df.columns = ['INPUT', 'a', 'b']

    # create a new row
    new_row = pd.DataFrame({'INPUT': ['Name'], 'a': ['Age'], 'b':['City']})
    # concat the newly created row with the existing dataframe df
    df = pd.concat([new_row, df]).reset_index(drop=True)

    # rename the column, keep only the 'INPUT'
    df.columns = ['INPUT', '', '']
    df

    Continue reading...

Compartilhe esta Página