我一直在对我所拥有的数据框执行groupby操作,该数据框根据列'名称'
汇总列。Name | As | Bs | Cs | Note
Mark 3 4 7 Good
Luke 2 1 12 Well
Mark 5 6 8 Ok
John 1 18 3 Great
所以在这种情况下,行标有' Mark'使用以下代码聚合在A,B和C列上:
temp_df = temp_df.groupby(['Name'], as_index=False).agg({'As': np.sum, 'Bs': np.sum,'Cs': np.sum})
我需要添加的是计算' Name'中具有相同值的行数。这会给我一个输出,如:
Name | As | Bs | Cs | Note | Count
Mark 8 10 15 Good 2
Luke 2 1 12 Well 1
John 1 18 3 Great 1
如何修改上面的代码行来完成我需要的操作?
答案 0 :(得分:3)
创建群组并进行聚合:
.done
然后从the_group = temp_df.groupby(['Name'], as_index=False)
temp_df = the_group.agg({'As': np.sum, 'Bs': np.sum,'Cs': np.sum})
size
the_group
给出:
temp_df['count'] = the_group.count()['Note']
根据评论中的建议,如果数据包含 Name Cs As Bs count
0 John 3 1 18 1
1 Luke 12 2 1 1
2 Mark 15 8 10 2
,则使用size()
会更安全:
NaN
答案 1 :(得分:0)
使用issue #96 + first
,然后是dict所需的temp_df = temp_df.groupby('Name', sort=False) \
.agg({'As':np.sum,'Bs':np.sum,'Cs':np.sum,'Note':'first','Name':'size'}) \
.rename(columns={'Name':'Count'}) \
.reset_index() \
.reindex_axis(temp_df.columns.tolist() + ['Count'], axis=1)
print (temp_df)
Name As Bs Cs Note Count
0 Mark 8 10 15 Good 2
1 Luke 2 1 12 Well 1
2 John 1 18 3 Great 1
列:
count
请勿使用size
,仅使用len
或$("#checkboxid").on('click',function(){
$(this).data('old',$(this).val());
});
。