pandas groupby + unstack的使用
概述
groupby()可以根据DataFrame中的某一列或者多列内容进行分组聚合,当DataFrame聚合后为两列索引时,可以使用unstack()将聚合的两列中一列值调整为行索引,另一列的值调整为列索引。
代码说明
test_df = pd.DataFrame({ 'col_1':['a', 'a', 'b', 'a', 'a', 'b', 'c', 'a', 'c'],
'col_2':['d', 'd', 'd', 'e', 'f', 'e', 'd', 'f', 'f'],
'col_3':[ 1, 2, 3, 1, 4, 5, 6, 4, 5]})
1.仅对数据进行分组聚合
df1=test_df.groupby(['col_1', 'col_2']).count()
df1:
col_3
col_1 col_2
a d 2
e 1
f 2
b d 1
e 1
c