You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Pandas分组后的统计列添加列名?

问题:GroupBy分组后统计列无名称,如何命名?

我用groupby分组后得到的time_counts结果里,统计列没有名称,想把它命名为count,实现如下期望输出:

time                   count
2022-12-15 08:00:18    1
2022-12-15 08:07:17    1
2022-12-15 08:12:09    1
2022-12-15 08:12:19    1
2022-12-15 08:13:04    1

当前代码:

import pandas as pd

def read_data():
    df = pd.read_csv("test.csv", usecols=['time', 'unix_time', 'name'])
    df['time'] = pd.to_datetime(df['time'])
    df['unix_time'] = (df['unix_time']).astype(int)

    time_counts = df.groupby(df['time'].dt.floor('S'))['time'].count()
    print(time_counts)

if __name__ == "__main__":
    read_data()

几种可行的解决方式:

方式一:用rename()直接重命名统计列

在count()之后调用rename方法,直接给统计列指定名称:

import pandas as pd

def read_data():
    df = pd.read_csv("test.csv", usecols=['time', 'unix_time', 'name'])
    df['time'] = pd.to_datetime(df['time'])
    df['unix_time'] = (df['unix_time']).astype(int)

    time_counts = df.groupby(df['time'].dt.floor('S'))['time'].count().rename('count')
    print(time_counts)

if __name__ == "__main__":
    read_data()

方式二:用agg()方法指定聚合列名

这种方式更灵活,适合需要同时做多种聚合操作的场景,直接在agg里定义列名和对应的聚合函数:

import pandas as pd

def read_data():
    df = pd.read_csv("test.csv", usecols=['time', 'unix_time', 'name'])
    df['time'] = pd.to_datetime(df['time'])
    df['unix_time'] = (df['unix_time']).astype(int)

    time_counts = df.groupby(df['time'].dt.floor('S')).agg(count=('time', 'count'))
    print(time_counts)

方式三:重置索引并重命名(将分组列转为普通列)

如果希望time不是索引而是普通数据列,可以用reset_index()配合name参数:

import pandas as pd

def read_data():
    df = pd.read_csv("test.csv", usecols=['time', 'unix_time', 'name'])
    df['time'] = pd.to_datetime(df['time'])
    df['unix_time'] = (df['unix_time']).astype(int)

    time_counts = df.groupby(df['time'].dt.floor('S'))['time'].count().reset_index(name='count')
    print(time_counts)

以上三种方式都能得到你想要的输出格式。


内容的提问来源于stack exchange,提问作者ditrauth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 06:35:24