Is there a way to get counts of only specific item in a column?
To clarify, say I use:
countDat = df['country'].value_counts()
Then I'll get something like:
Australia 35
Brazil 32
USA 93
... and so on
Is there a way to only extract counts of Brazil? I just need the number 32 extracted from countDat
.
I know countDat[1]
will give Brazil but is there a way to search it through the key 'Brazil'?
We can count by using the value_counts() method. This function is used to count the values present in the entire dataframe and also count values in a particular column.
The count() is a built-in function in Python. It will return you the count of a given element in a list or a string. In the case of a list, the element to be counted needs to be given to the count() function, and it will return the count of the element. The count() method returns an integer value.
groupby() and pass the name of the column that you want to group on, which is "state" . Then, you use ["last_name"] to specify the columns on which you want to perform the actual aggregation. You can pass a lot more than just a single column name to . groupby() as the first argument.
How do you Count the Number of Occurrences in a data frame? To count the number of occurrences in e.g. a column in a dataframe you can use Pandas value_counts() method. For example, if you type df['condition']. value_counts() you will get the frequency of each unique value in the column “condition”.
One way is to drop down to numpy
:
res = (df['country'].values == 'Brazil').sum()
See here for benchmarking results from a similar problem.
You should see better performance if you are using Categorical Data, which also has other benefits.
consider the data frame df
df = pd.DataFrame(dict(country=np.array('AUS BRA USA'.split()).repeat([35, 32, 93])))
and value counts
countDat = df['country'].value_counts()
countDat
USA 93
AUS 35
BRA 32
Name: country, dtype: int64
df.loc[df.country == 'BRA', 'country'].count()
32
countDat["BRA"]
32
df.country.eq('BRA').sum()
query
+ len
len(df.query('country == "BRA"')
groupby
+ len
len(df.groupby('country').groups['BRA'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With