Pythonic在数据框中的列中创建值对的方法

时间:2017-02-21 18:31:48

标签: python pandas

我的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。有人会知道更好的方法吗?

非常感谢任何帮助。

5 个答案:

答案 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就是你所需要的。

根据您希望如何合并它们,例如,尝试permutationscombinations

答案 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]