[Python] How to break down a column which contains several different features, so that a new...

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

  1. Stack

    Stack Membro Participativo

    I want to break down a column which contains several different features, so that a new column is built for each feature, also taking as column name the feature name. I already tried with:

    data = {'col1': ["a=1", "b=2", "c=3"]}
    col1
    0 a=1
    1 b=2
    2 c=3

    df['col2'] = df['col1'].apply(lambda x: pd.Series(x[0]))
    df['col3'] = df['col1'].apply(lambda x: pd.Series(x[1]))
    df['col4'] = df['col1'].apply(lambda x: pd.Series(x[2]))

    #df['col5'] = df['col1'].apply(lambda x:x[3] if len(x) > 3 else None)
    print(df)
    new_df= df.drop('col1', axis=1)
    print(new_df)


    But the strings are split, this was the output:

    col2 col3 col4
    0 a = 1
    1 b = 2
    2 c = 3


    This is my input:

    Column1
    “Height = 12”
    …. (14 rows)
    “Height = 18”
    …. (16 rows)
    “Weight = 40”
    …. (17 rows)
    “Weight = 50”
    …. (3 rows)
    “Colour = red”
    …. (8 rows)
    “Colour = yellow”


    This is what I need:

    Height Weight Colour
    12 NaN NaN
    … (14 rows) … (14 rows) … (14 rows)
    18 NaN NaN
    … (16 rows) … (16 rows) … (16 rows)
    NaN 40 NaN
    … (17 rows) … (17 rows) … (17 rows)
    NaN 50 NaN
    … (3 rows) … (3 rows) … (3 rows)
    NaN NaN red
    … (8 rows) … (8 rows) … (8 rows)
    NaN NaN yellow
    … (2 rows) … (2 rows) … (2 rows)


    How to manage it? Thanks in advance.

    Continue reading...

Compartilhe esta Página