python - 基于两个数据框列构建计数字典
问题描述
我有一个看起来像这样的数据框:
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"
解决方案
使用collections.Counter
:
>>> from collections import Counter
>>> Counter(map(tuple, np.sort(df[['start','stop']], axis=1)))
{(1, 2): 2, (3, 4): 2}
这不会修改您的原始 DataFrame。
推荐阅读
- sass - 当页面重新加载时,Gulp watch with Livereload 重新加载,或者自己
- ansible - 使用 jinja2 的 ansible 库存组
- reactjs - 选择时 React Native TextInput 缩小,我该如何停止它?
- java - 在 Quarkus-Camel 中的任何其他类之前调用一个类
- php - 在第 22 行的 /usr/local/lib/php/pear/common.php 中打开所需的 'PEAR.php' (include_path='.:/usr/local/lib/php/pear') 失败
- r - 替换超出范围的值是指 r 中每一行的另一个数据框
- javascript - 有什么很棒的方法可以从数组中留下每个单独的元素吗?
- angularjs - 根据 ngIf 更改背景颜色
- javascript - 当onchange处理程序使用javascript检测长度为4时如何在状态文本框中自动添加连字符
- python - 如何在 Django 的数据表中创建过滤器列?