Python输出与元组列表中值相关的记录,由numpy确定

标签 python numpy median

我正在使用 numpy 从元组列表中查找中值,如下所示:

print(np.median( [x[1] for x in pairs]) )

本身来自collections.namedtuple ,并且它们单独看起来像这样:

Pair(hash=u'0x034c9e7f28f136188ebb2a2630c26183b3df90c387490159b411cf7326764341', gas=21000)
Pair(hash=u'0xffda7269775dcd710565c5e0289a2254c195e006f34cafc80c4a3c89f479606e', gas=1000000)
Pair(hash=u'0x90ca439b7daa648fafee829d145adefa1dc17c064f43db77f573da873b641f19', gas=90000)
Pair(hash=u'0x7cba9f140ab0b3ec360e0a55c06f75b51c83b2e97662736523c26259a730007f', gas=40000)
Pair(hash=u'0x92dedff7dab405220c473aefd12e2e41d260d2dff7816c26005f78d92254aba2', gas=21000)

这是我确定中位数的方法:

pairs = list(_as_pairs(dict_hash_gas))
# pprint.pprint(pairs)
if pairs:
    # Avoid a ValueError from min() and max() if the list is empty.
    print(min(pairs, key=lambda pair: pair.gas))
    print(max(pairs, key=lambda pair: pair.gas))
    print(np.median( [x[1] for x in pairs]) )

以下是结构的创建方式:

def _as_pairs(pairs):
    for pair in pairs:
        # TODO:  Verify the dict conatains exactly one item?
        for k, v in pair.items():
            # Should the `key` string also be an integer?
            #yield Pair(key=int(k, base=16), value=int(v))
            yield Pair(hash=k, gas=int(v))

完整的脚本可以是健全的here .

目前的输出是这样的:

Pair(hash=u'0xf4f034e23b4118cb4aa4e9d077f0f28d675e25e9dc2650225f32ac33e04c93aa', gas=21000)
Pair(hash=u'0x92de9056a6357752a46dff1d6ff274d204d450bbd6c51cefe757f199af105cb4', gas=4712388)
90000.0

问题是,如何输出与中值相关的整个记录​​、整个,而不是仅输出中值本身?

最佳答案

可以得到中位数Pair的索引,但是还需要一行:

1) 如果总是有 len(pairs)%2 == 1,则中位数是唯一的并且属于对:

gases = np.array([pair.gas for pair in pairs])
medianGasIndex = np.where( gases == np.median(gases) )[0][0]
print(pairs[medianGasIndex])

2) 如果你可能有len(pairs)%2 == 0,那么你必须选择:

2.1) 您想要的中值对是真实中值的最接近值(即第 50 个百分位,不包含在数据集中)

medianGasIndex = np.where( gases == np.percentile(gases,50,interpolation='nearest') )[0][0]

2.2) 或者您想要左右中值

leftMedianGasIndex = np.where( gases == np.percentile(gases,50,interpolation='lower') )[0][0]
rightMedianGasIndex = np.where( gases == np.percentile(gases,50,interpolation='higher') )[0][0]

它适用于此 minimal working example ,只需根据您的需要编辑获取中值的方式即可。

关于Python输出与元组列表中值相关的记录,由numpy确定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46302035/

相关文章:

python - 正则表达式在 Python 3 中将文本与分隔符匹配

python - 如果我系统地删除第 n 个随机数,随机数仍然是随机的吗?

python - 替代 numpy.argwhere 以加速 python 中的循环

python - 如何解决Django中的Unknown Field Error

python - 间隙填充轮廓/线

python - 我怎样才能从 CondaUpgradeError "A newer version of conda is required."中解脱出来?

python - numpy.gradient 函数的反函数

java - 选择中位数作为枢轴

image - 将像素排序为中值过滤器

language-agnostic - 在没有数据结构的情况下寻找中位数