[Python] How to efficiently categorize column in Pandas (no pd.cut)?

Discussão em 'Python' iniciado por Stack, Junho 19, 2025.

  1. Stack

    Stack Membro Participativo

    I have a large dataframe (millions of rows) and I want to categorize a numerical column into ordered labels, but I want to give names only to some specific values and put all other values into the "transient" category. Using pd.cut looks cumbersome and tricky in some cases.
    Is there an efficient way to get the same result of the example code?

    import pandas as pd

    MODES = [0, 9, 15, 25, 40]
    CATS = 'B BC/2 BC AB ABC'.split()

    # Build categorical type
    my_cats = pd.CategoricalDtype(categories=['transient', 'B', 'BC/2', 'BC', 'AB', 'ABC'], ordered=True)

    # The data to be categorized
    df = pd.DataFrame(data=[-3, 1.99, 0, 3, 9, 12, 15, 17, 24.9999999, 25, 25.000000001, 34, 40-1e-13, 40], columns=['val'])

    # Building...
    df['cat'] = df['val'].replace(dict(zip(MODES, CATS)))
    c_ = ~df['cat'].isin(CATS)
    df.loc[c_, 'cat'] = 'transient'
    df['cat'] = df['cat'].astype(my_cats)

    # What I want
    print(df)

    Continue reading...

Compartilhe esta Página