Python 基于两个数据帧列构建计数Dict
我有一个如下所示的数据帧:Python 基于两个数据帧列构建计数Dict,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,我有一个如下所示的数据帧: start stop 0 1 2 1 3 4 2 2 1 3 4 3 我正试图从元组列表中构建一个包含key=(start,stop)对的字典,其出现的次数为value=count,而不考虑顺序。换言之,(1,2)和(2,1)都将算作元组列表中成对(1,2)的出现 所需输出:dict_count={('1','2'):2,('3','4'):2} 以下是我的尝试: my_list=[('1'
start stop
0 1 2
1 3 4
2 2 1
3 4 3
我正试图从元组列表中构建一个包含key=(start,stop)对的字典,其出现的次数为value=count,而不考虑顺序。换言之,(1,2)和(2,1)都将算作元组列表中成对(1,2)的出现
所需输出:dict_count={('1','2'):2,('3','4'):2}
以下是我的尝试:
my_list=[('1','2'),('3','4')]
但是,这给了我一个关键错误:
keyrerror:“['1'…]不在索引中”
使用值+排序
然后我们执行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}
使用集合。计数器
:
>>> from collections import Counter
>>> Counter(map(tuple, np.sort(df[['start','stop']], axis=1)))
{(1, 2): 2, (3, 4): 2}
这不会修改原始数据帧。谢谢;我的df还有很多其他的专栏。df.values.sort()
会保留其他列中的顺序吗?@Caerus btw如果它对您有用,请不要忘记upvote和accept:-)找到alt:)
>>> from collections import Counter
>>> Counter(map(tuple, np.sort(df[['start','stop']], axis=1)))
{(1, 2): 2, (3, 4): 2}