我的Dataframe
看起来像这样:
OwnerID Value
1 A
1 B
1 C
1 D
这是缩短版本,我有OwnerID
的数千个值。我想为Value
列创建配对,其中每个Value
与其他Value
配对,并将结果作为配对列表。
例如,对于OwnerID
1,结果集应该是以下列表:
[A,B]
[A,C]
[A,D]
[B,C]
[B,D]
[C,D]
我可以编写2个for
循环来实现这一目标,但这不是非常有效或pythonic。有人会知道更好的方法吗?
非常感谢任何帮助。
答案 0 :(得分:5)
Pandas解决方案(使用here和.merge()方法):
数据:
In [9]: pd.merge(df, df, on='OwnerID', suffixes=['','2']).query("Value != Value2")
Out[9]:
OwnerID Value Value2
1 1 A B
2 1 A C
3 1 A D
4 1 B A
6 1 B C
7 1 B D
8 1 C A
9 1 C B
11 1 C D
12 1 D A
13 1 D B
14 1 D C
17 2 X Y
18 2 X Z
19 2 Y X
21 2 Y Z
22 2 Z X
23 2 Z Y
解决方案:
In [17]: pd.merge(df, df, on='OwnerID', suffixes=['','2']) \
.query("Value != Value2") \
.filter(like='Value').values
Out[17]:
array([['A', 'B'],
['A', 'C'],
['A', 'D'],
['B', 'A'],
['B', 'C'],
['B', 'D'],
['C', 'A'],
['C', 'B'],
['C', 'D'],
['D', 'A'],
['D', 'B'],
['D', 'C'],
['X', 'Y'],
['X', 'Z'],
['Y', 'X'],
['Y', 'Z'],
['Z', 'X'],
['Z', 'Y']], dtype=object)
如果您只需要列表:
$('.box').click(function() {
$('.box').each( function() {
if ($(this).offset().left < 0) {
$(this).css("left", "150%");
}
});
$(this).animate({
left: '-50%'
}, 500);
if ($(this).next().size() > 0) {
$(this).next().animate({
left: '50%'
}, 500);
} else {
$(this).prevAll().last().animate({
left: '50%'
}, 500);
}
});
答案 1 :(得分:4)
import itertools as iter
df2 = df.groupby('OwnerID').Value.apply(lambda x: list(iter.combinations(x, 2)))
将为每个唯一所有者ID
返回所需的输出OwnerID
1 [(A, B), (A, C), (A, D), (B, C), (B, D), (C, D)]
答案 2 :(得分:1)
itertools
就是你所需要的。
根据您希望如何合并它们,例如,尝试permutations
或combinations
。
答案 3 :(得分:0)
尝试itertools
import itertools
list(itertools.combinations(['a','b','c','d'], 2))
#result: [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
答案 4 :(得分:0)
val = df['Value'].values
length = len(val)
pairs = [[val[i],val[j]] for i in xrange(length) for j in xrange(length) if i!=j]