Please help me find a solution for this: I have a Pandas DataFrame containing website visitors and date of their visit. Now I want to know, how many people visit once, twice, etc.
I start with a table:
Visitor | Date
---------------------
A | Jan-1st
B | Jan-1st
C | Jan-2nd
D | Jan-2nd
A | Jan-2nd
I want to end up with a result in the form of:
Frequency | No. of
of visits | visitors
-----------------------
1 | 3
2 | 1
In pandas you can get the count of the frequency of a value that occurs in a DataFrame column by using Series. value_counts() method, alternatively, If you have a SQL background you can also get using groupby() and count() method.
Using the count(), size() method, Series. value_counts(), and pandas. Index. value_counts() method we can count the number of frequency of itemsets in the given DataFrame.
To count the frequency of a value in a DataFrame column in Pandas, we can use df. groupby(column name). size() method.
After grouping a DataFrame object on one column, we can apply count() method on the resulting groupby object to get a DataFrame object containing frequency count. This method can be used to count frequencies of objects over single or multiple columns.
Usevalue_count
on Visitor
column twice.
In [182]: df.Visitor.value_counts().value_counts()
Out[182]:
1 3
2 1
Details
First get, visitor-wise visits, then you get group the similar counts.
In [183]: df.Visitor.value_counts()
Out[183]:
A 2
D 1
B 1
C 1
Name: Visitor, dtype: int64
In [188]: (df.Visitor.value_counts()
.value_counts()
.reset_index()
.rename(columns={'index': 'Freq of visits', 'Visitor': 'No. of visitors'}))
Out[188]:
Freq of visits No. of visitors
0 1 3
1 2 1
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