2014-02-19 44 views
4

我有兩個相同大小的矢量,一個用於波高,另一個用於單獨對應於測量時間的相同時間點。我想知道有多少時間的兩個特定的數據被重複,例如:如何計算數組中重複一對特定值的次數?

HS = [0.5 1.0 2.3 0.5 0.5]

的Tm = [2.0 2.5 2.0 2.0 3.0]

這樣你就可以見:

HS的Tm計數

0.5 2.0 2

0.5 2.5 0

0.5 3.0 1

1.0 2.0 0

1.0 2.5 1 ...

我嘗試,但會出現以下的錯誤,因爲我出現整個行和列沒有數據,並且當我看到我的信息用於值。

from numpy import * 
from matplotlib.pyplot import * 
import matplotlib.pyplot as plt 
from time import * 

clf; cla; close 
dat = loadtxt("ecmwf.dat", unpack=True) 
HSf = dat[0,:] 
HSf = around(HSf,decimals=1) 
TMf = dat[1,:] 
TMf = around(TMf,decimals=1) 
mmat = zeros((31,141)) 

vhs = linspace(0.0,3.0,31) 
vtm = linspace(0.0,14.0,141) 

for i in xrange(0, vtm.size): 
for k in xrange(0, vhs.size): 
    if all((k <= vhs.size) & (i <= vtm.size)): 
     lg1 = (TMf == vtm[i]) & (HSf == vhs[k]) 
     lg2 = sum(lg1) 
    if lg2>=1: 
     fg1 = text(i,k, str(lg2),horizontalalignment='center', verticalalignment='center',fontsize=6) 
    mmat[k,i] = lg2 
+0

我認爲我有第一個最完整的答案,是我提供了你想要的,還是你想要零計數? –

回答

1

我建議使用Counter來算你對。

from collections import Counter 

Hs = [0.5, 1.0, 2.3, 0.5, 0.5] 
Tm = [2.0, 2.5, 2.0, 2.0, 3.0] 

occurrences = Counter(zip(Hs, Tm)) 
for h in sorted(set(Hs)): 
    for t in sorted(set(Tm)): 
     print h, t, occurrences[(h,t)] 

結果:

0.5 2.0 2 
0.5 2.5 0 
0.5 3.0 1 
1.0 2.0 0 
1.0 2.5 1 
1.0 3.0 0 
2.3 2.0 1 
2.3 2.5 0 
2.3 3.0 0 
1

Counter爲蟒2集合模塊中提供。7:

import collections 

Hs = [0.5, 1.0, 2.3, 0.5, 0.5] 

Tm = [2.0, 2.5, 2.0, 2.0, 3.0] 

pairs = zip(Hs, Tm) 

,我們可以壓縮的iterables在一起,整齊地配對起來:

>>> print(list(pairs)) 
[(0.5, 2.0), (1.0, 2.5), (2.3, 2.0), (0.5, 2.0), (0.5, 3.0)] 

所以

pairs = zip(Hs, Tm) 
counts = collections.Counter(pairs) 

print(counts) 

打印:

Counter({(0.5, 2.0): 2, (1.0, 2.5): 1, (0.5, 3.0): 1, (2.3, 2.0): 1}) 

而且,由於計數器是隻是字典的一個子類,我們可以翻譯吃它像一個字典:

for pair, count in counts.items(): 
    print(pair, count) 

打印出:

(1.0, 2.5) 1 
(0.5, 3.0) 1 
(0.5, 2.0) 2 
(2.3, 2.0) 1 

如果你想對那些不存在的罪名,與一對,就像在一個字典的關鍵訪問計數器:

counts[(1.0, 3.0)] 

回報

0 
0

你可以使用一個collections.Counter此任務

import collections 
import itertools 

hs = 0.5, 1.0, 2.3, 0.5, 0.5 
tn = 2.0, 2.5, 2.0, 2.0, 3.0 

pairCount = collections.Counter(itertools.izip(hs, tm)) 

print(pairCount) 

應該導致這樣的:

Counter({(0.5, 2.0): 2, (1.0, 2.5): 1, (2.6, 2.0): 1, (0.5, 3.0): 1}) 
0

collections.Counter()將計算在迭代ocerrances數量:

>>> import numpy as np 
>>> from collections import Counter 
>>> Hs = [0.5, 1.0, 2.3, 0.5, 0.5] 
>>> Tm = [2.0, 2.5, 2.0, 2.0, 3.0] 
>>> repeats = Counter(zip(Hs,Tm)) 
>>> 
>>> aHs = np.array(Hs) 
>>> aTm = np.array(Tm) 
>>> aRepeats = Counter(zip(aHs,aTm)) 
>>> aRepeats 
Counter({(0.5, 2.0): 2, (2.2999999999999998, 2.0): 1, (1.0, 2.5): 1, (0.5, 3.0): 1}) 
>>> 
>>> aRepeats[(0.5, 2.0)] 
2 
>>> repeats[(1.0, 2.5)] 
1 
>>> 
+0

所以我慢了出發的塊 - 不知道我是否應該刪除這個或沒有。 – wwii

相關問題