How to get the mode of a column in pandas where there are few of the same mode values pandas

試著忘記壹切 提交于 2021-02-05 08:09:31

问题


I have a data frame and i'd like to get the mode of a specific column. i'm using:

freq_mode = df.mode()['my_col'][0]

However I get the error:

ValueError: ('The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()', 'occurred at index my_col')

I'm guessing it's because I have few mode that are the same. I need any of the mode, it doesn't matter. How can I use any() to get any of the mode existed?


回答1:


For me your code working nice with sample data.

If necessary select first value of Series from mode use:

freq_mode = df['my_col'].mode().iat[0]



回答2:


We can see the one column

df=pd.DataFrame({"A":[14,4,5,4,1,5], 
                 "B":[5,2,54,3,2,7], 
                 "C":[20,20,7,3,8,7], 
                 "train_label":[7,7,6,6,6,7]}) 
X=df['train_label'].mode()
print(X)

DataFrame

    A   B   C  train_label
0  14   5  20            7
1   4   2  20            7
2   5  54   7            6
3   4   3   3            6
4   1   2   8            6
5   5   7   7            7

Output

0    6
1    7
dtype: int64


来源:https://stackoverflow.com/questions/57668270/how-to-get-the-mode-of-a-column-in-pandas-where-there-are-few-of-the-same-mode-v

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!