【问题标题】:Error when counting group by columns in Python-TypeError: only integer scalar arrays can be converted to a scalar index在 Python-TypeError 中按列计数分组时出错:只能将整数标量数组转换为标量索引
【发布时间】:2021-04-01 09:11:30
【问题描述】:

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

我的数据框:

 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

这是我想要的输出:

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

【问题讨论】:

  • 要获取每组的元素个数,只需使用 df.groupby("hour").size()
  • @tanglef 它不起作用。我犯了同样的错误。但我想要所有行上的不同,而不仅仅是小时。我在问题中添加了我正在寻找的他的输出。
  • 好吧,那么对多列进行groupby,可以在groupby中给出列名的列表。
  • @tanglef 同样的错误——这是我试图运行的 df_count= df.groupby(['hour', 'index','name']).size()
  • 您的列的 dtype 是什么?您可以粘贴代码来重建您的确切数据框吗?

标签: python pandas


【解决方案1】:

我不确定您的数据是怎么回事。当我这样设置时:

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()

【讨论】:

  • 谢谢!我解决了列类型的问题,并且您的代码有效。
猜你喜欢
  • 2020-04-30
  • 2020-07-23
  • 2020-03-12
  • 2019-01-09
  • 2020-04-20
  • 2019-03-15
  • 2020-09-24
  • 2021-01-17
  • 2019-04-26
相关资源
最近更新 更多