[Python] Pandas dont drop level of multindex when getting first value

Discussão em 'Python' iniciado por Stack, Dezembro 19, 2024.

  1. Stack

    Stack Membro Participativo

    Example

    import pandas as pd
    import numpy as np
    t=pd.DataFrame({'c1': {(1, 1, 1): 1, (1, 2, 9): 2, (2, 1, 3): np.nan, (2, 1, 7): 4, (4, 2, 2): 6}, 'c2': {(1, 1, 1): 3, (1, 2, 9): 3, (2, 1, 3): 3, (2, 1, 7): 1, (4, 2, 2): 2}})
    print(t["c1"].groupby(level=[0,1]).first())


    output

    1 1 1.0
    2 2.0
    2 1 4.0
    4 2 6.0
    Name: c1, dtype: float64


    Desired:

    1 1 1 1.0
    2 9 2.0
    2 1 7 4.0
    4 2 2 6.0
    Name: c1, dtype: float64



    Answer doesn't need to be a groupby, I feel like there has to be a way to use a slice on the iloc of an index that respects nans

    Continue reading...

Compartilhe esta Página