如何计算数组中重复一对特定值的次数?

时间:2014-02-19 19:46:44

标签: python python-2.7

我有两个相同大小的矢量,一个用于波高,一个用于与测量时间相同的时间段相对应的周期。我想知道重复两个特定数据的次数,例如:

Hs = [0.5 1.0 2.3 0.5 0.5]

Tm = [2.0 2.5 2.0 2.0 3.0]

所以你可以看到:

Hs Tm Count

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

4 个答案:

答案 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 :(得分:1)

Counter在python 2.7的collections模块中可用:

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)

我们可以将迭代器压缩在一起以整齐地配对它们:

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

由于Counter只是dict的一个子类,我们可以将它视为一个dict:

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

答案 2 :(得分: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})

答案 3 :(得分:0)

collections.Counter()将计算iterable中的ocerrance数:

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