从按另一列分组的 pandas 列中的列表中查找频繁出现的元素

Find the frequent elements from a list in pandas column grouped by another column

我的数据框如下所示

col1      col2
type1     ['A','C','B','D']
type1     ['C','A','F','E']
type1     ['F','E','G','H']
type2     ['A','E','F','G']
type2     ['A','E','J','K']

我必须从 col2 的列表中找出给定用户输入中经常出现的元素。 例如,如果用户输入是 A。那么我们必须找到与 A 一起出现的前 3 个元素。并且必须为 col1 中的每个值计算这个。 即

type1 - most frequent element for A - A,C will be the output
type2 - most frequent element for A - A,E will be the output

此处发布的数据为示例数据。

from collections import Counter

def most_freq(series, input_):
    cnt = Counter()
    for row in series:
        if input_ in row:
            for i in row:
                cnt[i] += 1
    return [k for (k,v) in cnt.most_common(2)]

query = 'A'
df.groupby('col1').agg({'col2': lambda x: most_freq(x, query)})

输出:

        col2
col1    
type1   [A, C]
type2   [A, E]

解释:

解决此问题的一种可能方法是使用自定义 aggregate 函数。

它使用 Counter 来收集每一行中元素的所有计数,如果 user input 出现,则按 col1 分组,并且 return 它的前 2 个出现。如果您正在寻找前 3 次出现,OP 可以将 cnt.most_common(2) 中的参数 2 更改为 3

def func(_list):
    a = _list
    b = [a.count(i) for i in a ]
    c = pd.DataFrame({'Letter':a,
                      'Count':b})
    d = c[c['Count'] == c['Count'].max()]
    e = d['Letter'].unique()
    f = np.array(e,dtype = object)
    return f

df = pd.DataFrame({'col1':['type1','type1','type1','type2','type2'],
               'col2':[['A','C','B','D'],['C','A','F','E'],['F','E','G','H'],['A','E','F','G'],['A','E','J','K']]
              })

df = df.groupby('col1').sum()

df['col3'] = df['col2'].apply(lambda x: func(x))

df

我希望我理解你的问题 - 你想要与 A:

相邻的前 3 个项目
from collections import Counter

def fn(x):
    c = Counter()
    for row in x:
        s = pd.Series(row)
        m = s == 'A'
        c.update(s[m.shift(fill_value=False) | m.shift(-1, fill_value=False)])
    return c.most_common(3)

print( df.groupby('col1').col2.apply(fn) )

打印:

col1
type1    [(C, 2), (F, 1)]
type2            [(E, 2)]
Name: col2, dtype: object

CA的2次邻居,Ftype1

中只有一次

EA 的 2 倍邻居,在 type2


如果你想要最常见的,你可以在fn():

return list(dict(c.most_common(1)).keys())

这会打印:

col1
type1    [C]
type2    [E]
Name: col2, dtype: object