我有一个看起来像这样的数据框:
start stop
0 1 2
1 3 4
2 2 1
3 4 3
我试图用元组列表中的key =(开始,停止)对和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"
答案 0 :(得分:4)
使用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
如果您需要dict
df.groupby(df.columns.tolist()).size().to_dict()
{("'1'", "'2'"): 2, ("'3'", "'4'"): 2}
更新
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}
答案 1 :(得分:4)
使用collections.Counter
:
>>> from collections import Counter
>>> Counter(map(tuple, np.sort(df[['start','stop']], axis=1)))
{(1, 2): 2, (3, 4): 2}
这不会修改您的原始DataFrame。