从n x k DataFrame中,生成一个(n超过2)x 2k的所有行对的DataFrame。

问题描述 投票:0回答:1

给定一个尺寸为n x k的pandas DataFrame x,我们怎样才能做到 高效 生成一个尺寸为(n大于2)x 2k的DataFrame y,它的行是所有可能的行的组合,从x? 例如,如果x是

[[1 11],
 [2,22],
 [3,33],
 [4,44]]

那么y应该是

[[1,11,2,22],
 [1,11,3,33],
 [1,11,4,44],
 [2,22,3,33],
 [2,22,4,44],
 [3,33,4,44]]
pandas numpy matrix reshape
1个回答
2
投票

我们可以尝试 combinations

from itertools import combinations
[*map(lambda x : sum(x,[]),combinations(l,r=2))]
Out[80]: 
[[1, 11, 2, 22],
 [1, 11, 3, 33],
 [1, 11, 4, 44],
 [2, 22, 3, 33],
 [2, 22, 4, 44],
 [3, 33, 4, 44]]

1
投票

我的尝试

l=[[1,11], [2,22], [3,33], [4,44]]

全部名单

#lst=[x+y for x in [z for z in l[:3]] for y in [z for z in l[1:]] if x!=y]#Use + in list comprehension

如果你想消除 [3, 33, 2, 22].初始化一个新的 list 并附上 x+y 唯有 y+x 不存在。

k=[]
lst=[k.append(x+y) for x in [z for z in l[:3]] for y in [z for z in l[1:]] if x!=y if y+x not in k]
print(k)

enter image description here


0
投票

通过修改巴拉特的答案 此处,我产生了一个解决方案。

n=4; x=pandas.DataFrame([[i,11*i] for i in range(1,n+1)],columns=['A','B'])
cnct=( lambda l,i=0: pandas.concat(l,axis=i) )
z=cnct([ cnct([x.iloc[:i] for i in range(n)]).sort_index().reset_index(drop=True), 
         cnct([x.iloc[i+1:] for i in range(n)]).reset_index(drop=True) ], 1)

在n=10**4的情况下,它比itertools的解决方案要好.

© www.soinside.com 2019 - 2024. All rights reserved.