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

2024-06-02 06:16:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个大小相同的向量,一个是波高向量,一个是周期向量,分别对应于测量的同一时间点。我想知道这两个特定数据重复了多少次,例如:

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

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

Tags: 数据fromimportsizematplotlib向量dattm
3条回答

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)

我们可以将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})

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

如果你想知道不存在的对的数量,就用对访问计数器,就像dict中的键一样:

counts[(1.0, 3.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})

我建议用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

相关问题 更多 >