[英]Count occurences of a row with pandas in python
我有一個具有數千行和4列的熊貓數據框。 即:
A B C D
1 1 2 0
3 3 2 1
3 1 1 0
....
有什么方法可以計算某行發生多少次? 例如,可以找到多少次[3,1,1,0],並返回這些行的索引?
如果您只尋找一行,那么我可能會做類似的事情
>>> df.index[(df == [3, 1, 1, 0]).all(axis=1)]
Int64Index([2, 3], dtype=int64)
-
解釋如下。 從...開始:
>>> df
A B C D
0 1 1 2 0
1 3 3 2 1
2 3 1 1 0
3 3 1 1 0
4 3 3 2 1
5 1 2 3 4
我們與目標進行比較:
>>> df == [3,1,1,0]
A B C D
0 False True False True
1 True False False False
2 True True True True
3 True True True True
4 True False False False
5 False False False False
找到匹配的:
>>> (df == [3,1,1,0]).all(axis=1)
0 False
1 False
2 True
3 True
4 False
5 False
並使用以下布爾系列從索引中進行選擇:
>>> df.index[(df == [3,1,1,0]).all(axis=1)]
Int64Index([2, 3], dtype=int64)
如果您不是要計算一行的發生,而是想為每一行重復執行此操作,因此您確實想同時定位所有行,那么比一次又一次地執行上述操作要快得多。 但這對於一行來說應該已經足夠好了。
首先創建一個示例數組:
>>> import numpy as np
>>> x = [[1, 1, 2, 0],
... [3, 3, 2, 1],
... [3, 1, 1, 0],
... [0, 1, 2, 3],
... [3, 1, 1, 0]]
然后創建一個數組視圖,其中每一行都是一個元素:
>>> y = x.view([('', x.dtype)] * x.shape[1])
>>> y
array([[(1, 1, 2, 0)],
[(3, 3, 2, 1)],
[(3, 1, 1, 0)],
[(0, 1, 2, 3)],
[(3, 1, 1, 0)]],
dtype=[('f0', '<i8'), ('f1', '<i8'), ('f2', '<i8'), ('f3', '<i8')])
對要查找的元素執行相同的操作:
>>> e = np.array([[3, 1, 1, 0]])
>>> tofind = e.view([('', e.dtype)] * e.shape[1])
現在,您可以查找該元素:
>>> y == tofind[0]
array([[False],
[False],
[ True],
[False],
[ True]], dtype=bool)
您還可以使用MultiIndex,對它進行排序后,可以更快地找到計數:
s = StringIO("""A B C D
1 1 2 0
3 3 2 1
3 1 1 0
3 1 1 0
3 3 2 1
1 2 3 4""")
df = pd.read_table(s,delim_whitespace=True)
s = pd.Series(range(len(df)), index=pd.MultiIndex.from_arrays(df.values.T))
s = s.sort_index()
idx = s[3,1,1,0]
print idx.count(), idx.values
輸出:
2 [2 3]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.