python - 对列表的列表进行分组,并计算唯一的第一个元素的第二个元素的出现次数

标签 python list machine-learning group-by decision-tree

我试图找到分割决策树的最佳变量,它需要对某些值的出现进行分组和计数。 虚拟数据集是

zipped=[(‘a’, ‘None’), (‘b’, ‘Premium’), (‘c’, ‘Basic’), (‘d’, ‘Basic’), (‘b’, ‘Premium’), (‘e’, ‘None’), (‘e’, ‘Basic’), (‘b’, ‘Premium’), (‘a’, ‘None’), (‘c’, ‘None’), (‘b’, ‘None’), (‘d’, ‘None’), (‘c’, ‘Basic’), (‘a’, ‘None’), (‘b’, ‘Basic’), (‘e’, ‘Basic’)]

所以,我想知道 a、b、c、d、e 中分别有多少个 None、Basic 和 Premium 我需要它看起来像

{‘a’:[‘None’:3,‘Basic’:0,‘Premium’:0], ‘b’:[‘None’:1,‘Basic’:1,‘Premium’:3],…} .

我也愿意接受更好的聚合或数据结构方式。 这是我尝试做的事情

temp=Counter( x[1] for x in zipped  if x[0]=='b')
print(temp)

我得到了

Counter({'Premium': 3, 'None': 1, 'Basic': 1})

最佳答案

假设您的 ab 等是您的 slashdotgoogle:

zipped=[('a', 'None'), ('b', 'Premium'), ('c', 'Basic'), ('d', 'Basic'), ('b', 'Premium'), 
        ('e', 'None'), ('e', 'Basic'), ('b', 'Premium'), ('a', 'None'), ('c', 'None'), 
        ('b', 'None'), ('d', 'None'), ('c', 'Basic'), ('a', 'None'), ('b', 'Basic'), 
        ('e', 'Basic')]


from collections import Counter

d = {}
for key,val in zipped:
    d.setdefault(key,[]).append(val) # create key with empty list (if needed) + append val.

# now they are ordered lists, overwrite with Counter of it:
for key in d:
    d[key] = Counter(d[key])

print(d)

输出:

 {'a': Counter({'None': 3}), 
  'b': Counter({'Premium': 3, 'None': 1, 'Basic': 1}), 
  'c': Counter({'Basic': 2, 'None': 1}), 
  'd': Counter({'Basic': 1, 'None': 1}), 
  'e': Counter({'Basic': 2, 'None': 1})}

Counter 为您提供 .most_common() 来获取您想要的列表:

for k in d:
    print(k,d[k].most_common()) 

输出:

a [('None', 3)]
b [('Premium', 3), ('None', 1), ('Basic', 1)]
c [('Basic', 2), ('None', 1)]
d [('Basic', 1), ('None', 1)]
e [('Basic', 2), ('None', 1)]

如果您确实需要 0 计数,您可以在事后添加它们:

allVals = {v for _,v in zipped}   # get distinct values of zipped
for key in d:
    for v in allVals:
        d[key].update([v])        # add value once
        d[key].subtract([v])      # subtract value once

有点麻烦,但这样所有的东西都会出现,如果 zipped 中不存在则值为 0

for k in d:
    print(k,d[k].most_common()) 

输出:

a [('None', 3), ('Premium', 0), ('Basic', 0)]
b [('Premium', 3), ('None', 1), ('Basic', 1)]
c [('Basic', 2), ('None', 1), ('Premium', 0)]
d [('Basic', 1), ('None', 1), ('Premium', 0)]
e [('Basic', 2), ('None', 1), ('Premium', 0)]

关于python - 对列表的列表进行分组,并计算唯一的第一个元素的第二个元素的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49700936/

相关文章:

python - Pandas 变换()与应用()

python - python 2.7 中的网络带宽测试或速度测试

html - 如何使用 :nth-child? 将背景应用于无序列表

python - 根据顶级域(edu、com、org、in)对列表进行排序

python - 为什么我的用于检测图像旋转的卷积模型对每张图片预测相同的类别?

python - 使用进化算法实现对抗性示例生成器表现不佳

python - 使用一个 QPushButton 和两个 QLineEdit,具体取决于最后一个焦点

Python MySQLdb : Query parameters as a named dictionary

python - 将列表拆分为较小的列表(分成两半)

machine-learning - 多线程训练神经网络时,没有数据访问同步,这正常吗?