通过使用python中的字段值来计数ID [英] Count ID's by using field values in python
本文介绍了通过使用python中的字段值来计数ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张桌子
Id Brand1 Brand2 Brand3 Brand4
0 1 0 0 1
1 1 0 1 0
2 1 0 1 0
3 1 1 0 0
4 1 1 0 1
,并且我正在尝试使用品牌组合创建一个ID数量表.
and I am trying to create a table for the number of Ids using brand in combinations.
Brand1 Brand2 Brand3 Brand4
Brand1 - 2 2 2
Brand2 2 - 0 1
Brand3 2 0 - 0
Brand4 2 1 0 -
由于它们具有相同的值,因此也可以使用.
since they have the same values this would work, too.
Brand1 Brand2 Brand3 Brand4
Brand1 - 2 2 2
Brand2 - - 0 1
Brand3 - - - 0
Brand4 - - - -
推荐答案
您可以使用简单的矩阵乘积来做到这一点:
You can do that with a simple matrix product:
import pandas as pd
df = pd.DataFrame({
'Brand1': [1, 1, 1, 1, 1],
'Brand2': [0, 0, 0, 1, 1],
'Brand3': [0, 1, 1, 0, 0],
'Brand4': [1, 0, 0, 0, 1],
})
cross = df.T @ df
print(cross)
# Brand1 Brand2 Brand3 Brand4
# Brand1 5 2 2 2
# Brand2 2 2 0 1
# Brand3 2 0 2 0
# Brand4 2 1 0 2
这篇关于通过使用python中的字段值来计数ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文