Pandas:如何按列元素的组合分组,以指示基于不同列的值的同现? [英] Pandas: How to groupby combinations of column elements to indicate co-occurrence based on the values of a different column?
本文介绍了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:如何按列元素的组合分组,以指示基于不同列的值的同现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文