gpt4 book ai didi

python - 如何从 pandas 的 groupby 函数中获取列数的新数据框?

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:11 24 4
gpt4 key购买 nike

我根据 created_at_hour 对我的数据进行分组并计算总和。我这样做没问题。但是,我想获得一个只有这两列的新数据框。我该怎么做?

这是我的数据示例

created_at, user_id
xxx, x

这就是我到目前为止所做的。

data.created_at = pd.to_datetime(data.created_at)
data['created_at_minute'] = data.apply(lambda row: row['created_at'].minute, axis=1)
data['created_at_day'] = data.apply(lambda row: row['created_at'].day, axis=1)
data['created_at_hour'] = data.apply(lambda row: row['created_at'].hour, axis=1)
group_by = data.groupby(['created_at_hour']).agg(['count'])
group_by.plot()

我得到这样的图表。

enter image description here

一切都很好,但现在我想要一个新的数据框,其中只有 created_at_hour 和来自 groupby 的新的 count 列我怎么能去做?这是目前的结果。

enter image description here

最佳答案

您可以执行 data.groupby(['created_at_hour']).created_at.agg(['count']) 仅对一列进行聚合(在本例中为 created_at )。那么您生成的 DataFrame 将只有一列。它仍然会有一个 MultiIndex 列索引,因为您使用了 .agg(['count']) (传递一个单元素列表)。如果您只想进行一次聚合,则可以改用 .agg('count') 或仅使用 .count()

关于python - 如何从 pandas 的 groupby 函数中获取列数的新数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34686619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com