[英]python: count events by certain id
我有以下數組[] []:
import numpy as np
data = np.array([
[20, 0, 1],
[22, 0, 1],
[31, 0, 0],
[49, 1, 0],
[96, 1, 0],
[57, 2, 1],
[45, 3, 0],
[12, 3, 0],
[14, 3, 1],
[33, 4, 1],
[34, 4, 1],
[15, 4, 1]
])
讓我們通過上面的順序調用列: a, b, c
,其中b is id
。 我想通過列b
的id計算c
列中1的數量,這將導致以下2列數組(第1列是唯一的(b),第2列從c
每個id計算1):
data = np.array([
[4, 3],
[0, 2],
[2, 1],
[3, 1],
[1, 0]
])
您還可以看到它按c
列中的計數1排序
我解決這個問題的想法是通過b列中的id創建一個dictionery: { id1:counted 1's id2:counted 1's ... }
並迭代數組並計算每個id的1的數量並將其作為值在字典中的每個鍵,然后從結果中創建一個數組並按第二列排序。
有沒有pythonic容易和更好的方法這樣做?
另一種情況是我想在每個id的c列中添加所有整數,所以對於:
data = np.array([
[20, 0, 2],
[22, 0, 1],
[31, 0, 0],
[49, 1, 0],
[96, 1, 0],
[57, 2, 1],
[45, 3, 0],
[12, 3, 5],
[14, 3, 1],
[33, 4, 1],
[34, 4, 3],
[15, 4, 4]
])
我會得到
data = np.array([
[4, 8],
[3, 6],
[0, 3],
[2, 1],
[1, 0]
])
你可以使用np.bincount
-
count = np.bincount(data[:,1],data[:,2]==1)
out = np.column_stack((np.unique(data[:,1]),count))
如果按照計數的降序需要它,我們需要再添加兩行代碼 -
sidx = count.argsort()[::-1]
out = np.column_stack((sidx,count[sidx]))
另外,如果你需要它在遞減計數的順序,還可以保持這個順序,使用argsort
與'mergesort'
,像這樣-
sidx = (-count).argsort(kind='mergesort')
out = np.column_stack((sidx,count[sidx]))
樣品運行 -
輸入數組:
In [36]: data
Out[36]:
array([[20, 0, 1],
[22, 0, 1],
[31, 0, 0],
[49, 1, 0],
[96, 1, 0],
[57, 2, 1],
[45, 3, 0],
[12, 3, 0],
[14, 3, 1],
[33, 4, 1],
[34, 4, 1],
[15, 4, 1]])
第1部分 :
In [37]: count = np.bincount(data[:,1],data[:,2]==1)
...: out = np.column_stack((np.unique(data[:,1]),count))
...:
In [38]: out
Out[38]:
array([[ 0., 2.],
[ 1., 0.],
[ 2., 1.],
[ 3., 1.],
[ 4., 3.]])
第2部分 :
In [39]: sidx = count.argsort()[::-1]
...: out = np.column_stack((sidx,count[sidx]))
...:
In [40]: out
Out[40]:
array([[ 4., 3.],
[ 0., 2.],
[ 3., 1.],
[ 2., 1.],
[ 1., 0.]])
第3部分:
In [48]: sidx = (-count).argsort(kind='mergesort')
In [49]: np.column_stack((sidx,count[sidx]))
Out[49]:
array([[ 4., 3.],
[ 0., 2.],
[ 2., 1.],
[ 3., 1.],
[ 1., 0.]])
要在每個id的c列中添加所有整數,只需跳過對1
檢查 -
count = np.bincount(data[:,1],data[:,2])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.