I am still new to Python pandas' pivot_table
and would like to ask a way to count frequencies of values in one column, which is also linked to another column of ID. The DataFrame looks like the following.
import pandas as pd df = pd.DataFrame({'Account_number':[1,1,2,2,2,3,3], 'Product':['A', 'A', 'A', 'B', 'B','A', 'B'] })
For the output, I'd like to get something like the following:
Product A B Account_number 1 2 0 2 1 2 3 1 1
So far, I tried this code:
df.pivot_table(rows = 'Account_number', cols= 'Product', aggfunc='count')
This code gives me the two same things. What is the problems with the code above? A part of the reason why I am asking this question is that this DataFrame is just an example. The real data that I am working on has tens of thousands of account_numbers.
Using the size() or count() method with pandas. DataFrame. groupby() will generate the count of a number of occurrences of data present in a particular column of the dataframe.
count() function is used to count occurrences of pattern in each string of the Series/Index. This function is used to count the number of times a particular regex pattern is repeated in each of the string elements of the Series. Valid regular expression. For compatibility with other string methods.
To count the frequency of a value in a DataFrame column in Pandas, we can use df. groupby(column name). size() method.
Use Sum Function to Count Specific Values in a Column in a Dataframe. We can use the sum() function on a specified column to count values equal to a set condition, in this case we use == to get just rows equal to our specific data point. If we wanted to count specific values that match another boolean operation we can.
You need to specify the aggfunc
as len
:
In [11]: df.pivot_table(index='Account_number', columns='Product', aggfunc=len, fill_value=0) Out[11]: Product A B Account_number 1 2 0 2 1 2 3 1 1
It looks like count, is counting the instances of each column (Account_number
and Product
), it's not clear to me whether this is a bug...
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