[Python] group by multiple columns and perfume custom aggregation

Discussão em 'Python' iniciado por Stack, Agosto 16, 2025.

  1. Stack

    Stack Membro Participativo

    I have this dataframe which has multiple id's and facid's. I want to group by the three columns and apply a custom function or use built in pivot function to get the expected output. input is like this

    df1 = pd.DataFrame({
    'id': [18614, 18614, 18614, 18650, 18650, 18709, 18709],
    'facid': [140065, 140065, 140065, 140339, 140339, 140702, 140703],
    'location': ['dc','dc','dc','md','md','md','va'],
    'key': [433,442,443, 434, 444, 442, 443],
    'value1':['yes',7,3,'yes',4,5,6],
    'value2':['stage1','NA','NA','stage2','NA','NA','NA']})


    and I expect the output be like this... I also want to set a default value of 999 for the two numeric columns

    df2 = pd.DataFrame({
    'id': [18614,18650,18709,18709],
    'facid': [140065, 140339, 140702, 140703],
    'location': ['dc','md','md','va'],
    'length':[7,999,5,999],
    'width':[3,999,999,6],
    'stage': ['stage1','stage2','None','None']})

    Continue reading...

Compartilhe esta Página