问题
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