Good afternoon, tell me how to remove a row from the header of the table of this frame, which contains NaN? enter image description here

Came to this with such code:

data = df.groupby(['Тип газопровода', 'Диаметр'])['Протяженность'] data = data.agg([{'Средняя протяженность':'mean', 'Кол-во объектов':'count', 'Общая протяженность':'sum'}]) data = data.reset_index(col_level=True) 

    1 answer 1

    Replace:

     [{'Средняя протяженность':'mean', 'Кол-во объектов':'count', 'Общая протяженность':'sum'}] 

    on

     {'Средняя протяженность':'mean', 'Кол-во объектов':'count', 'Общая протяженность':'sum'} 

    Example:

    Source DataFrame:

     In [94]: df Out[94]: type dm length 0 1 50 110 1 1 50 111 2 1 63 112 3 2 32 113 4 2 32 114 5 2 32 115 6 3 50 116 7 3 50 117 8 3 50 118 9 3 80 119 

    Decision:

     In [95]: funcs = { ...: 'count': 'count', ...: 'total length': 'sum', ...: 'avg. length': 'mean' ...: } ...: In [96]: df.groupby(['type','dm'])['length'].agg(funcs).reset_index() Out[96]: type dm count total length avg. length 0 1 50 2 221 110.5 1 1 63 1 112 112.0 2 2 32 3 342 114.0 3 3 50 3 351 117.0 4 3 80 1 119 119.0 

    for comparison, your option:

     In [97]: df.groupby(['type','dm'])['length'].agg([funcs]).reset_index() Out[97]: type dm NaN count total length avg. length 0 1 50 2 221 110.5 1 1 63 1 112 112.0 2 2 32 3 342 114.0 3 3 50 3 351 117.0 4 3 80 1 119 119.0 

    Universal version of the transformation of multi-level columns into ordinary ones:

     In [98]: rslt = df.groupby(['type','dm'])['length'].agg([funcs]).reset_index() In [99]: rslt Out[99]: type dm NaN count total length avg. length 0 1 50 2 221 110.5 1 1 63 1 112 112.0 2 2 32 3 342 114.0 3 3 50 3 351 117.0 4 3 80 1 119 119.0 In [100]: rslt.columns = [tup[1] if tup[1] else tup[0] for tup in rslt.columns] In [101]: rslt Out[101]: type dm count total length avg. length 0 1 50 2 221 110.5 1 1 63 1 112 112.0 2 2 32 3 342 114.0 3 3 50 3 351 117.0 4 3 80 1 119 119.0 
    • good day! Thanks for the help, but this decision does not work on my data. It still remains NaN and an extra level. And how is my decision different from yours? The same methods, the same order of use, I only have lines and variables one more. - Denis Novik
    • @DenisNovik, the difference is that you use the [{...}] construct, and I use {...} - MaxU
    • had seen! Thank you very much, now everything turned out as it should. You are on the pandas branch the main guru! - Denis Novik
    • @DenisNovik, always happy to help :-) - MaxU