簡體   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