python - 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
也许这更清楚?
解决方案
如果你想要排列或组合,我不是 100% 清楚,但这段代码的工作原理是一样的——你可能只需要根据情况交换permutations
for 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
推荐阅读
- python - 无法用folium绘制地图
- python - import pyttsx3 as engine 和 engine = pyttsx3.init() 有什么区别?
- c# - C# 使用静态方法并传入数据库读取器
- asp.net-core - 在 C# 中使用 Microsoft Graph api 如何使用 azure Ad 身份验证在我的应用程序中获取当前登录用户(活动会话)的列表
- c - 指针设置为 NULL 但不在调试器中
- python - 如何使用 tkinter 实现监听器?
- flutter - Flutter Listview.Separated 在列表的开头和结尾添加分隔符
- sql - 在多个不相关表中的多个字段之间应用 COALESCE
- javascript - 如何将 postgres 查询分配给 node.js、Discord bot 和 postgres 集成中的变量?
- python - Python 安装旧版本的 matplotlib 导致 freetype 和 png 错误