使用“groupby”方法后获取 Dataframe 的所有列

Getting all columns of a Dataframe after using 'groupby' method

提问人:Kumar-58 提问时间:4/19/2019 最后编辑:user3483203Kumar-58 更新时间:4/19/2019 访问量:225

问:

应用 Pandas 的 groupby 方法后无法获取 Dataframe 的所有列

我有一个示例数据帧,如下所示。

  col1 col2        day col4
0   a1   b1     monday   c1
1   a2   b2    tuesday   c2
2   a3   b3  wednesday   c3
3   a1   b1     monday   c5

这里“a1 b1 monday”重复了两次。因此,在 groupby 之后,输出应该是:

col1    col2          day     col4  count
a1        b1       monday      c1     2
a2        b2      tuesday      c2     1
a3        b3    wednesday      c3     1

我试过使用df.groupby(['col1','day'],sort=False).size().reset_index(name='Count')

df.groupby(['col1','day']).transform('count')

输出始终是

col1    day         count
a1  monday        2
a2  tuesday       1
a3  wednesday     1

其中,由于我的原始数据有 14 列,因此将所有列名保留在 groupby 语句中是没有意义的。有没有更好的pythonic方法来实现这一目标?

python-3.x pandas-groupby

评论

0赞 user3483203 4/19/2019
df.groupby(['col1', 'day'])['col4'].agg(['first', 'count']).reset_index()
0赞 Kumar-58 4/19/2019
正如我所提到的,真实数据总共有 14 列,其中大字符串作为列名,因此将所有 14 列名保留在 groupby 语句中并不是一个令人愉快的方式

答:

1赞 Erfan 4/19/2019 #1

首先使用转换来制作你的列。groupbycount

然后使用 drop_duplicates 删除重复的行:

df['count'] = df.groupby(['col1','day'],sort=False)['col1'].transform('size')
df.drop_duplicates(['col1', 'day'], inplace=True)

print(df)
  col1 col2        day col4  count
0   a1   b1     monday   c1      2
1   a2   b2    tuesday   c2      1
2   a3   b3  wednesday   c3      1

评论

0赞 Kumar-58 4/19/2019
也已经尝试过drop_duplicates(忘了在帖子中提及)。我希望获取所有列以及“日”列上的出现次数
0赞 Erfan 4/19/2019
编辑答案 @Kumar-58
0赞 Erfan 4/20/2019
完美,如果它对你有帮助,请不要忘记接受答案 :) @Kumar-58