我有以下数据框
import pandas as pd
import numpy as np
df = pd.DataFrame()
df['Name'] = ['AK', 'Ram', 'Ram', 'Singh', 'Murugan', 'Kishore', 'AK']
df['Email'] = ['AK@gmail.com', 'a@djgbj.com', 'a@djgbj.com', '3454@ghhg.io', 'dgg@qw.cc', 'dgdg@dg.com', 'AK@gmail.com']
df['Cat'] = ['ab1', 'ab2', 'ab1', 'ab2', 'ab1', 'ab2', 'ab1']
df['Id'] = ['abc1', 'abc2', 'abc3', 'abc4', 'abc5', 'abc6', 'abc7']
对于以下代码
dfs=df.groupby(['Email', 'Cat'])['Email'].count().reset_index(name='Number')
它给出:
Email Cat Number
0 3454@ghhg.io ab2 1
1 AK@gmail.com ab1 2
2 a@djgbj.com ab1 1
3 a@djgbj.com ab2 1
4 dgdg@dg.com ab2 1
5 dgg@qw.cc ab1 1
如何在dfs上分组以获取以下输出?
Cat Number Count
ab1 1 3
ab1 2 1
ab2 1 3
答案 0 :(得分:4)
使用groupby
+ size
和reset_index
:
df1 = dfs.groupby(['Cat','Number']).size().reset_index(name='Count')
或者:
df1 = dfs.groupby(['Cat','Number'])['Email'].value_counts().reset_index(name='Count')
print(df1)
Cat Number Count
0 ab1 1 2
1 ab1 2 1
2 ab2 1 3
答案 1 :(得分:1)
简单地:
dfs.groupby(['Cat', 'Number']).count()
复制了下面的内容,有效。
>>> dfs.groupby(['Cat', 'Number']).count()
Email
Cat Number
ab1 1 2
2 1
ab2 1 3
OR
>>> dfs.groupby(['Cat', 'Number'])['Email'].count()
Cat Number
ab1 1 2
2 1
ab2 1 3
Name: Email, dtype: int64