【问题标题】:Getting all columns of a Dataframe after using 'groupby' method使用“groupby”方法后获取数据框的所有列
【发布时间】:2019-04-18 22:38:07
【问题描述】:

应用 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方法来实现这一点??

【问题讨论】:

  • df.groupby(['col1', 'day'])['col4'].agg(['first', 'count']).reset_index()
  • 正如我提到的,真实数据共有 14 列,以大字符串作为列名,因此将所有 14 个列名保留在 groupby 语句中并不是一种愉快的方式

标签: python-3.x pandas pandas-groupby


【解决方案1】:

首先groupbytransform 组成您的count 列。

然后使用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

【讨论】:

  • 也已经尝试过 drop_duplicates(忘了在帖子中提及)。我希望获取所有列以及“日”列上的出现次数
  • 编辑答案@Kumar-58​​span>
  • 完美,如果对你有帮助,别忘了接受作为答案:) @Kumar-58​​span>
猜你喜欢
  • 1970-01-01
  • 2021-10-15
  • 2020-10-16
  • 1970-01-01
  • 2022-12-03
  • 2020-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多