繁体   English   中英

Python-TypeError: only integer scalar arrays can be converted to a scalar index 中按列计数时出错

[英]Error when counting group by columns in Python-TypeError: only integer scalar arrays can be converted to a scalar index

我想每小时计算重复行数。

我的数据框:

 hour         index    name    
08:00:00      1442       x
08:45:00      3434       y
08:30:00      1442       x
08:00:00      1442       x
08:45:00      3434       y
08:00:00      1442       x

我的代码:我试图对每小时的数据进行分组并计数。 转换没有帮助。

df_count= df.groupby('hour')[['index','name']].count()

这是错误:

TypeError: only integer scalar arrays can be converted to a scalar index

这是我想要的 output:

 hour         index    name   count  
08:00:00      1442       x       3
08:30:00      1442       x       1
08:45:00      3434       y       2

我不确定您的数据发生了什么。 当我这样设置时:

df = pd.DataFrame({
    'hour': ['08:00:00', '08:45:00', '08:30:00', '08:00:00', '08:45:00', '08:00:00'],
    'index': [1442, 3434, 1442, 1442, 3434, 1442],
    'name': ['x', 'y', 'x', 'x', 'y', 'x'],
})

然后你的代码工作正常(它不做你想要的,但它运行没有问题):

>>> df.groupby('hour')[['index','name']].count()
          index  name
hour                 
08:00:00      3     3
08:30:00      1     1
08:45:00      2     2

无论如何,一旦您修复了 DataFrame 内容,以下内容应该会得到预期的结果:

>>> df.groupby(['hour', 'index', 'name']).size()
hour      index  name
08:00:00  1442   x       3
08:30:00  1442   x       1
08:45:00  3434   y       2

如果愿意,您还可以添加: .to_frame('count').reset_index()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM