Python返回一对数字列表的线性/累积对

时间:2016-06-01 20:27:07

标签: python pandas list

我有一个pandas数据框,它有许多不同表格的混乱连接。我想将这些表分段并对它们执行操作。我有一个表头位置列表,如下所示:[1,4,5,7,9,12,15] - 所以第一个表的标题位于索引1,第二个表的标题位于索引我的目标是使用这个列表来切割数据帧并从每个切片中提取信息,并将数据变成漂亮的东西。

我试图为此目的得到这样的对列表:[[1,4],[4,5],[5,7],[7,9],[9,12], [12,15]

我尝试了这个函数,但它没有完全返回我想要的东西,它返回这样的对:1,4,5,7,9,12 - 这让我跳过其他每一个表:/。

def pairwise(iterable): #this is what is wrong
    a = iter(iterable)
    return izip(a, a)

我错过了什么吗?我在这里疯了。

5 个答案:

答案 0 :(得分:1)

为什么不只是[[a[x], a[x+1]] for x in range(len(a)-1)]?假设a= [1, 4, 5, 7, 9, 12, 15]

答案 1 :(得分:0)

如何实现这个功能:

select sport,won, season_start, count(sport) as sportcount
from table1 where won = 'Y'
group by sport, won, season_start

因此,对于列表def pairwise(itr): return list(zip(itr[:-1], itr[1:])) ,此功能会压缩[1, 4, 5, 7, 9, 12, 15][1, 4, 5, 7, 9, 12],并返回预期的[4, 5, 7, 9, 12, 15]

答案 2 :(得分:0)

你必须有一个迭代器吗?您可以使用切片和typedef std::string string; 来获取所需对的列表。

zip

答案 3 :(得分:0)

问题在于izip每次都会从迭代器中取出一个项目,这就是成对结束的原因。这是形成迭代器的直接方法:

def pairwise(iterable):
    seq = iter(iterable)
    a = next(seq)
    for b in seq:
        yield a,b
        a = b

list(pairwise([1,2,3,4]))

输出:

[(1, 2), (2, 3), (3, 4)]

虽然如果你有这些清单,以下内容更紧凑:

L = [1,2,3,4]
list(zip(L[:-1], L[1:]))

使用来自itertools的tee和izip清理迭代器版本:

from itertools import tee, izip
def pairwise(iterable):
    L1, L2 = tee(iterable)
    next(L2)
    return izip(L1,L2)

三个版本的时间。请注意,第二个版本需要列表而不是迭代器,因此使用python 2.7 range vs xrange

%timeit list(pairwise(xrange(1000)))
10000 loops, best of 3: 97.3 µs per loop

%timeit list(pairwise(range(1000)))
10000 loops, best of 3: 51.1 µs per loop

%timeit list(pairwise(xrange(1000)))
10000 loops, best of 3: 60.6 µs per loop

答案 4 :(得分:0)

这应该适合你:

def pairwise(l1):
    l1Iter = iter(l1)
    pre = next(l1Iter)
    result = []
    for curr in l1Iter:
        result.append([pre, curr])
        pre = curr
    return result

或者,如果您不需要此列表和生成器,如果正常:

def pairwise_gen(l1):
    l1Iter = iter(l1)
    pre = next(l1Iter)
    for curr in l1Iter:
       yield pre, curr
       pre = curr