在Python中将列值转换为具有计数的列

2024-06-02 04:31:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个dataframe,我想在其中将列值分成列,并对类别求和,按2列分组

数据

tar date    ex  ppr stat
aa  q122    bb  10  hi
aa  q122    bb  15  hello
aa  q122    bb  10  hi
cc  q222    zz  20  hey
cc  q222    zz  15  hello

所需的

tar date    count   ppr_sum hi  hello   hey
aa  q122    3       35      2   1       0
cc  q222    2       35      0   1       1

df1 = pd.crosstab(index = [df['tar'], df['date']], columns = df['stat'])
ppr_sum = df1.groupby(['tar','date'])['ppr'].sum()

仍然无法获取stat列的和。如有任何建议,我们将不胜感激


Tags: hellodfdatetarhistataacc
1条回答
网友
1楼 · 发布于 2024-06-02 04:31:01

尝试使用get_dummiesgroupby

 >>> pd.get_dummies(df, prefix_sep='', prefix='', columns=['stat']).groupby(['tar', 'date'], as_index=False).sum().assign(count=df.groupby(['tar', 'date'], as_index=False)['ex'].size()['size'])
  tar  date  ppr  hello  hey  hi  count
0  aa  q122   35      1    0   2      3
1  cc  q222   35      1    1   0      2
>>> 

相关问题 更多 >