Return a mode value in a dataframe Python with condition

Viewed 428

I have one dataframe with 9 columns as below:

C0  C1  C2  C3  C4  C5  C6  C7  C8

1   1   1   0   0   1   0   0   0

1   1   1   0   4   0   0   2   3

1   1   1   0   0   2   4   1   3

0   2   0   0   1   0   0   0   0

0   2   0   2   0   0   4   1   3

0   2   0   2   4   0   4   1   3

0   2   0   2   4   0   4   1   3

0   2   0   0   4   0   4   1   3

I would like to return mode value of each column. I know that it can be done by using mode() in Python. However, I would like to add the condition that if there are >= 3 number "1" in the column, return mode=1 instead of the real mode of the column. And if there are >=4 number "2", return mode=2 instead of the real mode of the column. Else, return the real mode values.

The output of the code should be:

C0 C1 C2 C3 C4 C5 C6 C7 C8

 1  2  1  0  4  0  4  1  3

Please help me. Thank you.

2 Answers

Use mode to get the modes, then create boolean series to indicate if you should change to 1 or 2:

real_mode = df.mode(axis=0)
three_ones = (df == 1).sum(axis=0) >= 3
four_twos = (df == 2).sum(axis=0) >= 4

modified_mode = real_mode.loc[0]  # Extract the series, which gets named 0
modified_mode[three_ones] = 1
modified_mode[four_twos] = 2

the result is

C0    1
C1    2
C2    1
C3    0
C4    4
C5    0
C6    4
C7    1
C8    3
Name: 0, dtype: int64

Naive approach with counters:

from statistics import mode
from collections import Counter

counters = [( Counter(df[col].tolist()), col) for col in df.columns]
modes = [ 2 if c[0][2] >= 4 else 1 if c[0][1] >= 3 else mode(df[c[1]].tolist()) for c in counters]
Related