Meaning of mode() in pandas

Viewed 53
df5 = pd.DataFrame({"A": np.random.randint(0, 7, size=50),
                     "B": np.random.randint(-10, 15, size=50)})

df5.mode()


         A   B
    0  1.0  -9

    1  NaN  10

    2  NaN  13


Why does the NaN come from here?

1 Answers

Reason is if check DataFrame.mode:

Get the mode(s) of each element along the selected axis.

The mode of a set of values is the value that appears most often. It can be multiple values.

So missing values means for A is ony one mode value, for B column are 3 mode values, so for same rows are added missing values.

If check my sample data - there is mode A 2 times and B only once, because 2and 3 are both 11 times in data:

np.random.seed(20)
df5 = pd.DataFrame({"A": np.random.randint(0, 7, size=50), 
                    "B": np.random.randint(-10, 15, size=50)})

print (df5.mode())
   A    B
0  2  8.0
1  3  NaN

print (df5.A.value_counts())
3    11  <- both top1
2    11  <- both top1
6     9
5     8
0     5
1     4
4     2
Name: A, dtype: int64

print (df5.B.value_counts())
 8     6  <- only one top1
 0     4
 4     4
-4     3
 10    3
-2     3
 1     3
 12    3
 6     3
 7     2
 3     2
 5     2
-9     2
-6     2
 14    2
 9     2
-1     1
 11    1
-3     1
-7     1
Name: B, dtype: int64
Related