首页 > 解决方案 > Pandas 拆分列将每个项目迭代到两个新的对列

问题描述

我有一个如下所示的数据框,但经过简化,它可以是随机值的任何变化,而不仅仅是项目一、二、三等

在此处输入图像描述

然后我需要遍历 ID 列中的项目并为每个项目创建新的对

df2 = (pd.DataFrame({'ID': ['three', 'three', 'two', 'two', 'two', 'one', 'three', 'two', 'three', 'one'] , 
                'ID2':['two', 'one', 'three', 'one', 'one', 'two', 'two', 'three', 'one', 'three']}))

在此处输入图像描述

不太确定如何做到这一点,我知道 df 会很大。希望有人有一个有效的方法。

编辑:每对,如果你看不到图像,我的意思是

在示例中:

A|B|C

我有三个项目,所以我想为每个唯一对创建新行,所以它是

ID1     ID2
A        B
A        C
B        A
B        C
C        A
C        B

也许这更清楚?

标签: pythonpandas

解决方案


如果你想要排列或组合,我不是 100% 清楚,但这段代码的工作原理是一样的——你可能只需要根据情况交换permutationsfor combinations

我们首先要做的是获取数据框并在 | 上进行拆分。符号,然后我们使用 itertools 模块计算它的每个组合/排列。请参阅代码以了解其工作原理。

import itertools

def split_and_combine(x):
    # split the items on the '|' character
    split_items = x.split('|')
    
    # create permutations/combinations
    # the 2 means calculate pairs
    # change 'permutations' to 'combinations' if needed
    combined = itertools.permutations(split_items, 2)
    
    # return the result as a list
    return list(combined)
    
df['ID'] = df['ID'].apply(split_and_combine)

这给了我们...

                                                                                 ID
0  [(three, two), (three, one), (two, three), (two, one), (one, three), (one, two)]
1                                                          [(two, one), (one, two)]
2                                                      [(three, two), (two, three)]
3                                                      [(three, one), (one, three)]

现在我们需要将这些列表分开并将每个部分作为一个新行。我们将其放入一个新的数据框中。

df = df.explode('ID')

df现在等于...

             ID
0  (three, two)
0  (three, one)
0  (two, three)
0    (two, one)
0  (one, three)
0    (one, two)
1    (two, one)
1    (one, two)
2  (three, two)
2  (two, three)
3  (three, one)
3  (one, three)

现在我们将元组的每个部分放入两个单独的列中。

df['first'] = df['ID'].str[0]
df['second'] = df['ID'].str[1]

最后的结果整理好了,

result = df.drop('ID', axis=1).reset_index(drop=True)

result是....

    first second
0   three    two
1   three    one
2     two  three
3     two    one
4     one  three
5     one    two
6     two    one
7     one    two
8   three    two
9     two  three
10  three    one
11    one  three

推荐阅读