Get first and second highest values in pandas columns

后端 未结 5 1665
春和景丽
春和景丽 2020-12-15 05:34

I am using pandas to analyse some election results. I have a DF, Results, which has a row for each constituency and columns representing the votes for the various parties (o

5条回答
  •  死守一世寂寞
    2020-12-15 06:13

    Here is a solution using nlargest function:

    >>> df
        a   b   c
     0  4  20   2
     1  5  10   2
     2  3  40   5
     3  1  50  10
     4  2  30  15
    >>> def give_largest(col,n):
    ...     largest = col.nlargest(n).reset_index(drop = True)
    ...     data = [x for x in largest]
    ...     index = [f'{i}_largest' for i in range(1,len(largest)+1)]
    ...     return pd.Series(data,index=index)
    ...
    ...
    >>> def n_largest(df, axis, n):
    ...     '''
    ...     Function to return the n-largest value of each
    ...     column/row of the input DataFrame.
    ...     '''
    ...     return df.apply(give_largest, axis = axis, n = n)
    ...
    >>> n_largest(df,axis = 1, n = 2)
       1_largest  2_largest
    0         20          4
    1         10          5
    2         40          5
    3         50         10
    4         30         15
    >>> n_largest(df,axis = 0, n = 2)
                      a           b           c     
    1_largest         5          50           15
    2_largest         4          40           10
    

提交回复
热议问题