[Python] How to change texts in columns and then combine 1st row with the column headers?

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

  1. Stack

    Stack Membro Participativo

    I have the following dataframe:

    data={'a1':['X1',2,3,4,5],'Unnamed: 02':['Y1',5,6,7,8],'b1':['X2',5,3,7,9],'Unnamed: 05':['Y2',5,8,9,3],'c1':['X3',4,5,7,5],'Unnamed: 07':['Y3',5,8,9,3],'d1':['P',2,4,5,7],'Unnamed: 09':['M',8,4,6,7]}
    df=pd.DataFrame(data)
    df.columns=df.columns.to_series().mask(lambda x: x.str.startswith('Unnamed')).ffill()
    df


    [​IMG]

    There are a few things which I would like to do:

    1. Change the rows containing (X1, X2 & X3) into just 'X (vice versa for Y1,Y2,Y3 into 'Y)
    2. Combine the existing column header with the row containing X,Y,P,M

    The outcome should look like:

    1. Change the rows containing (X1, X2 & X3) into just 'X (vice versa for Y1,Y2,Y3 into 'Y)

    [​IMG]

    1. Combine the existing column header with the row containing X,Y,P,M - Also note that the 'P' and 'M' completely replaces 'd1' respectively.

    [​IMG]

    Continue reading...

Compartilhe esta Página