我正在尝试在我的numpy数组中对非常相似的值进行分组。
46.29821447,49.49781571,49.83072758,50.89081787,98.49113721,98.5522082,99.29547499,99.91765345,99.93779431,99.95351796,99.98066963,99.99294867,100
答案 0 :(得分:0)
搜索“Python group by”会引导您使用groupby
方法获取itertools的文档。在Stack Overflow上有关于如何使用它的examples。
from itertools import groupby
l = [46.29821447,49.49781571,49.83072758,50.89081787,98.49113721,98.5522082,99.29547499,99.91765345,99.93779431,99.95351796,99.98066963,99.99294867,100]
for key, group in groupby(l, round):
s = sorted(group)
print key, s[0], s[-1]
输出:
46.0 46.29821447 46.29821447
49.0 49.49781571 49.49781571
50.0 49.83072758 49.83072758
51.0 50.89081787 50.89081787
98.0 98.49113721 98.49113721
99.0 98.5522082 99.29547499
100.0 99.91765345 100
<强>更新强>
使用NumPy的floor
方法......
from itertools import groupby
import numpy as np
l = [46.29821447,49.49781571,49.83072758,50.89081787,98.49113721,98.5522082,99.29547499,99.91765345,99.93779431,99.95351796,99.98066963,99.99294867,100]
for key, group in groupby(l, np.floor):
s = sorted(group)
print key, s[0], s[-1]
输出:
46.0 46.29821447 46.29821447
49.0 49.49781571 49.83072758
50.0 50.89081787 50.89081787
98.0 98.49113721 98.5522082
99.0 99.29547499 99.99294867
100.0 100 100