基于两个数据框列构建一个计数字典

Cae*_*rus 3 python dataframe python-3.x pandas

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

    start   stop
0   1       2
1   3       4
2   2       1
3   4       3
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用我的元组列表中的 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
Run Code Online (Sandbox Code Playgroud)

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

WeN*_*Ben 5

使用values+sort然后我们就可以了groupby

df.values.sort()
df
  start stop
0   '1'  '2'
1   '3'  '4'
2   '1'  '2'
3   '3'  '4'
df.groupby(df.columns.tolist()).size()
start  stop
'1'    '2'     2
'3'    '4'     2
dtype: int64
Run Code Online (Sandbox Code Playgroud)

如果你需要dict

df.groupby(df.columns.tolist()).size().to_dict()
{("'1'", "'2'"): 2, ("'3'", "'4'"): 2}
Run Code Online (Sandbox Code Playgroud)

更新

df['orther']=1
df[['start','stop']]=np.sort(df[['start','stop']].values)
df.groupby(['start','stop']).size().to_dict()
{("'1'", "'2'"): 2, ("'3'", "'4'"): 2}
Run Code Online (Sandbox Code Playgroud)


cs9*_*s95 5

使用collections.Counter

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

这不会修改您的原始 DataFrame。