Answers for "pandas count occurrences in column group by"

1

pandas count occurrences in column

# Basic syntax:
df['column'].value_counts()

# Get normalized counts:
df['column'].value_counts(normalize=True)

# Example usage:
# Make dataframe
import pandas as pd
df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 5, 9]]), 
                  columns=['a', 'b', 'c'])

print(df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  5  9

df['b'].value_counts() # Returns:
5    2 # 5 appears twice in column 'b'
2    1

df['b'].value_counts(normalize=True) # Returns:
5    0.666667 # 5 accounts for 2/3 of the entries in column 'b'
2    0.333333
Posted by: Guest on May-24-2021
0

count occurrences of one variable grouped by another python

>>> data = pd.DataFrame({'user_id' : ['a1', 'a1', 'a1', 'a2','a2','a2','a3','a3','a3'], 'product_id' : ['p1','p1','p2','p1','p1','p1','p2','p2','p3']})
>>> count_series = data.groupby(['user_id', 'product_id']).size()
>>> count_series
user_id  product_id
a1       p1            2
         p2            1
a2       p1            3
a3       p2            2
         p3            1
dtype: int64
>>> new_df = count_series.to_frame(name = 'size').reset_index()
>>> new_df
  user_id product_id  size
0      a1         p1     2
1      a1         p2     1
2      a2         p1     3
3      a3         p2     2
4      a3         p3     1
>>> new_df['size']
0    2
1    1
2    3
3    2
4    1
Name: size, dtype: int64
Posted by: Guest on May-31-2020

Code answers related to "pandas count occurrences in column group by"

Python Answers by Framework

Browse Popular Code Answers by Language