根据另一列中的值汇总一列中的值

时间:2018-08-28 08:36:37

标签: python python-2.7 pandas

我有一个类似下面的数据框,

Timestamp                     count
20180702-06:26:20             50
20180702-06:27:11             10
20180702-07:05:10             20
20180702-07:10:10             30
20180702-08:27:11             40

我想输出类似下面的内容,

Timestamp                  Sum_of_count
20180702-06                   60
20180702-07                   50
20180702-08                   40

基本上,我需要找到每小时的总计数。 任何帮助都非常感谢。

2 个答案:

答案 0 :(得分:0)

您需要以某种方式设置单独的值-一个是split,然后先用str[0]列出列表,然后再汇总sum

s = df['Timestamp'].str.split(':', n=1).str[0]
df1 = df['count'].groupby(s).sum().reset_index(name='Sum_of_count')

或通过to_datetime将值转换为datetimes并通过strftime获取值:

df['Timestamp'] = pd.to_datetime(df['Timestamp'], format='%Y%m%d-%H:%M:%S')

s = df['Timestamp'].dt.strftime('%Y%m%d-%H')

df1 = df['count'].groupby(s).sum().reset_index(name='Sum_of_count')
print (df1)
     Timestamp  Sum_of_count
0  20180702-06            60
1  20180702-07            50
2  20180702-08            40

答案 1 :(得分:0)

使用

In [252]: df.groupby(df.Timestamp.dt.strftime('%Y-%m-%d-%H'))['count'].sum()
Out[252]:
Timestamp
2018-07-02-06    60
2018-07-02-07    50
2018-07-02-08    40
Name: count, dtype: int64

In [254]: (df.groupby(df.Timestamp.dt.strftime('%Y-%m-%d-%H'))['count'].sum()
             .reset_index(name='Sum_of_count'))
Out[254]:
       Timestamp  Sum_of_count
0  2018-07-02-06            60
1  2018-07-02-07            50
2  2018-07-02-08            40