首页 > 解决方案 > 基于两个数据框列构建计数字典

问题描述

我有一个看起来像这样的数据框:

    start   stop
0   1       2
1   3       4
2   2       1
3   4       3

我正在尝试使用我的元组列表中的 key= (start, stop) 对和 value= 它们出现的计数来构建字典,而不管顺序如何。换句话说,(1,2) 和 (2,1) 都将被视为在元组列表中出现的对 (1,2)。

期望的输出:dict_count= {('1','2'):2, ('3','4'):2}

这是我的尝试:

my_list=[('1','2'),('3','4')]

for pair in my_list:
    count=0
    if ((df[df['start']]==pair[0] and df[df['end']]==pair[1]) or (df[df['start']]==pair[1]) and df[df['end']]==pair[0])::
        count+=1
    dict_count[pair]=count

但是,这给了我一个 KeyError: KeyError: "['1' ...] not in index"

标签: pythonpython-3.xpandasdataframe

解决方案


使用collections.Counter

>>> from collections import Counter
>>> Counter(map(tuple, np.sort(df[['start','stop']], axis=1)))
{(1, 2): 2, (3, 4): 2}

这不会修改您的原始 DataFrame。


推荐阅读