Pandas: How to groupby combinations of column elements to indicate co-occurrence based on the values of a different column?(Pandas:如何按列元素的组合分组,以指示基于不同列的值的同现?)
本文介绍了Pandas:如何按列元素的组合分组,以指示基于不同列的值的同现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 pandas 数据帧,格式为df,
Batch_ID Product_ID
1 A
1 B
1 C
2 B
2 B
2 C
2 C
3 B
3 B
3 C
4 C
4 D
5 D
我想从中获得一个边列表,本质上是一个新的数据帧edge_list_df(我无法将其转换为networkx对象),
Source Target Weight
A B 1.0
A C 1.0
A D 0.0
B C 3.0
B D 0.0
C D 1.0
请注意,我在示例中给出了许多不同的可能性,以确保我的问题清晰。例如,即使对于BATCH_ID=2,B-C组合出现两次,计数器也不会增加两倍。
实现此目标的最有效方法是什么?
推荐答案
以下是我对它的看法:
from itertools import combinations
def combine(batch):
"""Combine all products within one batch into pairs"""
return pd.Series(list(combinations(set(batch), 2)))
edges = df.groupby('Batch_ID')['Product_ID'].apply(combine).value_counts()
edges
#(B, C) 3
#(A, B) 1
#(A, C) 1
#(D, C) 1
我知道实际上不需要0出现边。
如果需要,可以将索引进一步拆分为源和目标:
edges = edges.reset_index()
edges = pd.concat([edges, edges['index'].apply(pd.Series)], axis=1)
edges.drop(['index'], axis=1, inplace=True)
edges.columns = 'Weight','Source','Target'
# Weight Source Target
#0 3 B C
#1 1 A B
#2 1 A C
#3 1 D C
或:
c = ['Source', 'Target']
L = edges.index.values.tolist()
edges = pd.DataFrame(L, columns=c).join(edges.reset_index(drop=True))
这篇关于Pandas:如何按列元素的组合分组,以指示基于不同列的值的同现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:Pandas:如何按列元素的组合分组,以指示基于不同列的值的同现?


猜你喜欢
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 沿轴计算直方图 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12