不插值下采样列表中的条目数量
我有一个Python列表,里面有很多条目,我需要对这些条目进行降采样,也就是减少数量,方法有两种:
- 限制最大行数。比如说,把1234条目限制到1000条。
- 按比例减少原始行数。比如说,把列表缩减到原来的1/3。
(我需要能够同时使用这两种方法,但每次只用一种)。
我觉得对于最大行数的情况,我可以先计算出需要的比例,然后把这个比例传给按比例减少的函数:
def downsample_to_max(self, rows, max_rows):
return downsample_to_proportion(rows, max_rows / float(len(rows)))
...所以我其实只需要一个降采样的函数。有没有什么建议呢?
编辑:这个列表里面是对象,不是数字,所以我不需要插值。删除对象是可以的。
解决方案:
def downsample_to_proportion(self, rows, proportion):
counter = 0.0
last_counter = None
results = []
for row in rows:
counter += proportion
if int(counter) != last_counter:
results.append(row)
last_counter = int(counter)
return results
谢谢。
6 个回答
3
如果输入的数据已经是一个序列类型,比如列表或者元组,那么直接使用切片语法会比先用islice()
再用list()
更有效率。
def downsample_to_proportion(rows, proportion):
return rows[::int(1 / proportion)]
6
你可以使用来自 itertools
的 islice
:
from itertools import islice
def downsample_to_proportion(rows, proportion=1):
return list(islice(rows, 0, len(rows), int(1/proportion)))
用法:
x = range(1,10)
print downsample_to_proportion(x, 0.3)
# [1, 4, 7]
1
保持一个计数器,每次用第二个数值来增加它。每次都取整,然后返回那个位置的值。