[Python] Create new columns and fill with calculated values from same dataframe

Discussão em 'Python' iniciado por Stack, Abril 15, 2025.

  1. Stack

    Stack Membro Participativo

    Here is a simplified example of my df:

    ds = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])
    ds['sum'] = ds.sum(axis=1)


    which looks like

    A B C D sum
    1 0.095389 0.556978 1.646888 1.959295 4.258550
    2 1.076190 2.668270 0.825116 1.477040 6.046616
    3 0.245034 1.066285 0.967124 0.791606 3.070049


    I would like to create 4 new columns and calculate the percentage value from the total (sum) in every row. So first value in the first new column should be (0.095389/4.258550), first value in the second new column (0.556978/4.258550)...and so on.

    Continue reading...

Compartilhe esta Página