i have this dataframe:
0 name data
1 alex asd
2 helen sdd
3 alex dss
4 helen sdsd
5 john sdadd
so i am trying to get the most frequent value or values(in this case its values) so what i do is:
dataframe['name'].value_counts().idxmax()
but it returns only the value: Alex even if it Helen appears two times as well.
n = 2
a=dataframe['name'].value_counts()[:n].index.tolist()
dataframe["name"].value_counts()[a]
df['name'].value_counts()[:5].sort_values(ascending=False)
The value_counts
will return a count object of pandas.core.series.Series
and sort_values(ascending=False)
will get you the highest values first.
my best solution to get the first is
df['my_column'].value_counts().sort_values(ascending=False).argmax()
Use:
df['name'].mode()
or
df['name'].value_counts().idxmax()
Here's one way:
df['name'].value_counts()[df['name'].value_counts() == df['name'].value_counts().max()]
which prints:
helen 2
alex 2
Name: name, dtype: int64
Simply use this..
dataframe['name'].value_counts().nlargest(n)
The functions for frequencies largest and smallest are:
nlargest()
for mostfrequent 'n' valuesnsmallest()
for least frequent 'n' valuesTo get the top five most common names:
dataframe['name'].value_counts().head()
You could use .apply and pd.value_counts to get a count the occurrence of all the names in the name column.
dataframe['name'].apply(pd.value_counts)
You could try argmax
like this:
dataframe['name'].value_counts().argmax()
Out[13]: 'alex'
The value_counts
will return a count object of pandas.core.series.Series
and argmax
could be used to achieve the key of max values.
You can use this to get a perfect count, it calculates the mode a particular column
df['name'].value_counts()
Not Obvious, But Fast
f, u = pd.factorize(df.name.values)
counts = np.bincount(f)
u[counts == counts.max()]
array(['alex', 'helen'], dtype=object)
To get the n
most frequent values, just subset .value_counts()
and grab the index:
# get top 10 most frequent names
n = 10
dataframe['name'].value_counts()[:n].index.tolist()
to get top 5:
dataframe['name'].value_counts()[0:5]
Source: Stackoverflow.com