Python groupby 结果计数频率

标签 python pandas group-by

我有一个数据框

df = pd.DataFrame({'id':['one','one','two','two','three','three','three'],
                   'type':['current','saving','current','current','current','saving','credit']})

我想统计只有'current'的id的数量 应该是这样的:

only_currnt_id_list = ['two']

最佳答案

我认为你需要:

L = df.groupby('id') \
      .filter(lambda x: (x['type'] == 'current').all() and 
                        (x['type'] == 'current').sum() == 1)['id'].tolist()
print (L)

['two']

编辑:

df = pd.DataFrame({'id':['one','one','two','three','three','three'],'type':['current','current','current','current','saving','credit']})
print (df)
      id     type
0    one  current
1    one  current
2    two  current
3  three  current
4  three   saving
5  three   credit
<小时/>
L = df.groupby('id') \
      .filter(lambda x: (x['type'] == 'current').all() and 
                        (x['type'] == 'current').sum() == 1)['id'].tolist()
print (L)
['two']

L = df.groupby('id') \
      .filter(lambda x: (x['type'] == 'current').all())['id'].unique().tolist()
print (L)
['one', 'two']

关于Python groupby 结果计数频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45962154/

相关文章:

python - 在 Python 中传递多个不同的函数参数

python - 将序列导入Python

mysql - 将 SELECT DISTINCT ON 查询从 Postgresql 转换为 MySQL

MySQL从表1中检索最后一条记录并从表2中连接数据

python - pandas HDFStore - 如何重新打开?

python - 有没有办法跨进程修补对象?

python - Pandas v0.20 在乘以数据帧列时返回 NotImplemented

mysql - 获取超过 x 个订阅者的博客数量

python - 如何使用具有日期过滤器的 IF else 创建新列(替代 SAS then do)

json - 将 Pandas DataFrame 转换为 JSON 格式