您只能使用一个groupby 来提高性能:
df = (cat_df['depth'].ne(0)
.groupby(cat_df['category'])
.value_counts()
.unstack(fill_value=0)
.rename(columns={0:'depth=0', 1:'depth>0'})
.assign(total=lambda x: x.sum(axis=1))
.reindex(columns=['total','depth=0','depth>0']))
print (df)
depth total depth=0 depth>0
category
food 3 1 2
school 3 2 1
sport 1 0 1
解释:
- 首先比较
depth 列不等于 Series.ne (!=)
-
groupby 按列 category 和 SeriesGroupBy.value_counts
- 由
unstack重塑
-
Rename 字典列
- 由
assign 创建新的total 列
- 对于列的自定义顺序添加
reindex
编辑:
cat_df = pd.DataFrame({'category': ['food', 'food', 'sport', 'food', 'school', 'school', 'school'], 'depth': [0.0, 1.0, 1.0, 3.0, 0.0, 0.0, 1.0], 'num_of_likes': [10, 10, 10, 20, 20, 20, 20]})
print (cat_df)
category depth num_of_likes
0 food 0.0 10
1 food 1.0 10
2 sport 1.0 10
3 food 3.0 20
4 school 0.0 20
5 school 0.0 20
6 school 1.0 20
df = (cat_df['depth'].ne(0)
.groupby([cat_df['num_of_likes'], cat_df['category']])
.value_counts()
.unstack(fill_value=0)
.rename(columns={0:'depth=0', 1:'depth>0'})
.assign(total=lambda x: x.sum(axis=1))
.reindex(columns=['total','depth=0','depth>0'])
.reset_index()
.rename_axis(None, axis=1)
)
print (df)
num_of_likes category total depth=0 depth>0
0 10 food 2 1 1
1 10 sport 1 0 1
2 20 food 1 0 1
3 20 school 3 2 1
编辑1:
s = cat_df.groupby('category')['num_of_likes'].sum()
print (s)
category
food 40
school 60
sport 10
Name: num_of_likes, dtype: int64
df = (cat_df['depth'].ne(0)
.groupby(cat_df['category'])
.value_counts()
.unstack(fill_value=0)
.rename(columns={0:'depth=0', 1:'depth>0'})
.assign(total=lambda x: x.sum(axis=1))
.reindex(columns=['total','depth=0','depth>0'])
.reset_index()
.rename_axis(None, axis=1)
.assign(num_of_likes=lambda x: x['category'].map(s))
)
print (df)
category total depth=0 depth>0 num_of_likes
0 food 3 1 2 40
1 school 3 2 1 60
2 sport 1 0 1 10