Python split column将每个项迭代到成对的两个新列

Python split column将每个项迭代到成对的两个新列,python,pandas,Python,Pandas,我有一个如下的数据框,但经过简化,它可以是随机值的任何变化,而不仅仅是项目1、2、3等等 然后,我需要遍历ID列中的项,并创建每个项的新对 df2 = (pd.DataFrame({'ID': ['three', 'three', 'two', 'two', 'two', 'one', 'three', 'two', 'three', 'one'] , 'ID2':['two', 'one', 'three', 'one', 'one', 'two', 'tw

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

然后,我需要遍历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

也许这更清楚?

如果您想要排列或组合,我不是100%清楚,但这段代码的工作原理是一样的——您可能只需要将
排列
交换为
组合

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

导入itertools
def拆分和合并(x):
#拆分“|”字符上的项目
拆分项目=x.split(“|”)
#创建排列/组合
#2表示计算对
#如果需要,将“排列”更改为“组合”
组合=itertools.排列(拆分项,2)
#将结果作为列表返回
退货清单(合并)
df['ID']=df['ID']。应用(拆分和合并)
这给了我们

                                                                                 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)。重置索引(drop=True)
结果是

    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

不清楚你所说的“每一对都创建新的”是什么意思?这似乎就是我想要做的。非常感谢。