Python:具有最常见条目的数据子集

标签 python numpy pandas grouping subset

我正在努力解决以下问题。 想象一下,我有很多这样的数据:

one = {'A':'m','B':'n','C':'o'}
two = {'A':'m','B':'n','C':'p'}
three = {'A':'x','B':'n','C':'p'}

等等,不一定非要存储在dicts中。 我怎样才能获得包含最常见条目的数据子集?

在上面的例子中我想得到

one, two          with same A and B = m,n
two, three        with same B and C = n,p
one, two three    with same B       = n
one, two          with same A       = m

最佳答案

一种对长词典来说效率不高的方法是使用 itertools.combinations找到你的字典之间的组合,然后遍历组合,然后遍历集合,并得到集合项之间的交集:

one = {'one':{'A':'m','B':'n','C':'o'}}
two ={'two':{'A':'m','B':'n','C':'p'}}
three = {'three':{'A':'x','B':'n','C':'p'}}

dict_list=[one,two,three]
v_item=[i.items() for i in dict_list]

from itertools import combinations
names=[]
items=[]
l=[combinations(v_item,i) for i in range(2,4)]
flat=[[[t[0] for t in k] for k in j] for j in l]  
"""this line is for flattening the combinations i don't know why but python puts every elements within a list :
>>> l
[[([('one', {'A': 'm', 'C': 'o', 'B': 'n'})], [('two', {'A': 'm', 'C': 'p', 'B': 'n'})]), 
([('one', {'A': 'm', 'C': 'o', 'B': 'n'})], [('three', {'A': 'x', 'C': 'p', 'B': 'n'})]), 
([('two', {'A': 'm', 'C': 'p', 'B': 'n'})], [('three', {'A': 'x', 'C': 'p', 'B': 'n'})])], 
[([('one', {'A': 'm', 'C': 'o', 'B': 'n'})], [('two', {'A': 'm', 'C': 'p', 'B': 'n'})], [('three', {'A': 'x', 'C': 'p', 'B': 'n'})])]]"""


for comb in flat :
   for pair in comb:
     names,items =zip(*pair)
     items=[i.viewitems() for i in items]
     print names,reduce(lambda x,y:x&y,items) 

结果:

('one', 'two') set([('B', 'n'), ('A', 'm')])
('one', 'three') set([('B', 'n')])
('two', 'three') set([('B', 'n'), ('C', 'p')])
('one', 'two', 'three') set([('B', 'n')])

关于以下几行:

     items=[i.viewitems() for i in items]
     print names,reduce(lambda x,y:x&y,items)

您需要 c reate a view object of your items作为 set 对象,然后您可以计算项目与 & 操作数的交集。 使用 reduce功能。

关于Python:具有最常见条目的数据子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29963285/

相关文章:

python - 我如何使用 Python 获取包含特定文件(即'__main__.py)的子目录列表

python - -9999 作为 numpy.genfromtxt() 的缺失值

python - 将 "missing array values"写入文件

python - 将一个系列分配给 Pandas DataFrame 的多行

python pandas用数字替换数据框中的字符串

Python 继承基于 __init__ 值的魔术方法

python - sqlite3.操作错误: table book has 6 columns but 5 values were supplied

python - 不使用kv语言如何在kivy中绘制对象?

python - 如何在循环中使用 `numpy.savez`来保存多个numpy数组?

python - 替换DataFrame中的某些数字