[Python] Adding a new column in the first ordinal position in a pyspark dataframe

Discussão em 'Python' iniciado por Stack, Maio 13, 2025.

  1. Stack

    Stack Membro Participativo

    I have a pyspark data frame like:

    +--------+-------+-------+
    | col1 | col2 | col3 |
    +--------+-------+-------+
    | 25 | 01 | 2 |
    | 23 | 12 | 5 |
    | 11 | 22 | 8 |
    +--------+-------+-------+


    and I want to create new dataframe by adding a new column like this:

    +--------------+-------+-------+-------+
    | new_column | col1 | col2 | col3 |
    +--------------+-------+-------+-------+
    | 0 | 01 | 2 | 0 |
    | 0 | 12 | 5 | 0 |
    | 0 | 22 | 8 | 0 |
    +--------------+-------+-------+-------+


    I know I can add column by:

    df.withColumn("new_column", lit(0))


    but it adds column at last like this:

    +--------------+-------+-------+-------------+
    | col1 | col1 | col2 | new_column |
    +--------------+-------+-------+-------------+
    | 25 | 01 | 2 | 0 |
    | 23 | 12 | 5 | 0 |
    | 11 | 22 | 8 | 0 |
    +--------------+-------+-------+-------------+

    Continue reading...

Compartilhe esta Página