[Python] How to return one column dataframe or single row dataframe as a dataframe or a series?

Discussão em 'Python' iniciado por Stack, Fevereiro 27, 2025.

  1. Stack

    Stack Membro Participativo

    Given df,

    df = pd.DataFrame({'col1':np.arange(6), 'col2':[*'abcdef']})

    col1 col2
    0 0 a
    1 1 b
    2 2 c
    3 3 d
    4 4 e
    5 5 f


    Then when selecting a single column using:

    df['col1']
    # returns a pd.Series

    0 0
    1 1
    2 2
    3 3
    4 4
    5 5
    Name: col1, dtype: int32


    Likewise, when selecting a single row:

    df.loc[0]
    # returns a pd.Series

    col1 0
    col2 a
    Name: 0, dtype: object


    How can we force a single column or single row selection to return pd.DataFrame?

    Continue reading...

Compartilhe esta Página