python - 熊猫获得行组合和分组
问题描述
我有一个df
我必须找到 Group 的所有组合(比如说 2 对),然后必须将它们分组到唯一的 ID 中
输出:
目前我找到了一种生成所有组合的方法,但似乎无法按唯一 ID 分组
我也提到了下面的链接: Pandas 在预算内找到所有行组合
生成对的代码:
from itertools import combinations
li_4 =[]
for index in list(combinations(df.group.unique(),2)):
li_4.append([index[0],index[1]])
解决方案
我们可以这样做merge
并将np.sort
结果传递给crosstab
删除重复项后drop_duplicates
s = df.merge(df,on='Id')
s['New'] = list(map(lambda x : ''.join(x),np.sort(s[['Group_x','Group_y']].values,axis=1).tolist()))
s = s.drop_duplicates(['Id','New'])
s = pd.crosstab(s.Id,s.New)
s
Out[88]:
New aa ab ac ad af bb bc bd be bf cc cd dd de ee ff
Id
2 1 1 1 1 0 1 1 1 0 0 1 1 1 0 0 0
3 0 0 0 0 0 1 0 1 1 0 0 0 1 1 1 0
4 1 1 0 0 1 1 0 0 0 1 0 0 0 0 0 1
推荐阅读
- php - 在 PHP 中将过去的日期转换为星期几
- java - 如何使用 Java 中的 Streams 添加对象的属性?
- docker - github webhook 无法使用公共 ip 连接到 jenkins
- python-3.x - 我正在尝试在 python 脚本中创建 HTTP 服务器,但我无法通过脚本关闭服务器
- java - java - 如何通过文本字段值更新滑块位置
- python-3.x - 使用 Python 和 Pandas 我正在编写一个函数来查询一个字符串
- javascript - 如何将“html-minifier”连接到 gulp?
- html - 按钮与输入电子邮件不均匀?
- autohotkey - 当我添加 GUI 时,AHK 突然需要在 } 之前返回
- php - 发送邮件前使用 file_put_contents 打印