Why does Pandas df.mode() return a zero before the actual modal value?

Viewed 1255

When I run df.mode() on the below dataframe I get a leading zero before the expected output. Why is that?

df

sample       1   2   3   4   5   6   7   8   9   10
zone run                                                          
2    5      14   12  22  23  24  22  23  22  23  23 

print(df.iloc[:,3:10].mode(axis=1)))

gives

           0
zone run    
2    5    23

expecting

zone run    
2    5    23
2 Answers

pd.Series.mode

Return the mode(s) of the dataset. Always returns Series even if only one value is returned.

So that's how it is by design. A Series must have an index and it will start counting from 0. This ensures that the return type is stable regardless of whether there is only a single mode or multiple values tied for the mode.

So if you take a slice where values are tied for the mode, your return is a Series where the numbers 0, ...N are indicators for the N values tied for the mode (modal values in sorted order).

df.iloc[:, 4:7]
#sample     5   6   7
#zone run            
#2    5    24  22  23


df.iloc[:,4:7].mode(axis=1)
#           0   1   2       # <- 3 values tied for mode so 3 labels
#zone run            
#2    5    22  23  24

My thinking is, df.mode returns a dataframe. By default, dataframes if no column values are given allocates indices as column names. In this case,0 is allocated because that is how pandas/python begins count. Because it is a dataframe, the only way to change the column name which in this case is an index is to apply the .rename(columnn) method. Hence, to get what you need you will have to;

df1.iloc[:,3:10].agg('mode', axis=1).reset_index().rename(columns={0:''})

   zone run 
0   2    5   23
Related