python - 计算在组中排成一行的值?
问题描述
我有两个数据框:
id val
a w
a w
a l
a w
b w
b w
b w
c w
c l
d w
d w
d w
d w
我想获得在列 val 中的行中有 3 w 的 id。所以期望的结果必须是:
id
b
d
如您所见,只有 id b 和 d 在行中的列 val 中至少有 3 w。怎么做?
解决方案
不是最快的解决方案,但在这里:
import pandas as pd
import re # regular expression matching
df = <your_dataframe>
ids = [i for i in df.id.unique() if re.search('w{3}', ''.join(df[df.id==i].val))]
w{3}
意味着寻找 3 个连续的 'w's
编辑:没有正则表达式
import pandas as pd
df = pd.DataFrame({
"id": ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd', 'd', 'd'],
"val": ['w', 'w', 'l', 'w', 'w', 'w', 'w', 'w', 'l', 'w', 'w', 'w', 'w']
})
def threeInRow(values, match='w'):
count = 0
for i in range(len(values)):
if(values[i] == match):
count += 1
else:
count = 0
# "if three in a row, exit early"
if(count >= 3):
return True
return False
ids = [i for i in df.id.unique() if threeInRow(list(df[df.id==i].val)) ]
推荐阅读
- java - EHCache 本地 TransactionManager 删除时超时
- javascript - JavaScript - 具有无限循环的动态启动/停止功能
- macos - Mac Python IDLE 自动完成/弹出窗口不起作用
- excel - vb.net 创建电子表格,但手动关闭 excel 后仍然存在幻像进程
- vb.net - 表单对象未正确显示
- python - 如何通过求和值在numpy中组合矩阵的两列/行?
- php - MAMP 服务器上的本地 WordPress 站点不会显示使用高级自定义字段创建的所有字段
- jquery - JQuery平滑滚动错误
- c# - 将 SSL 证书转换为字节数组,然后再次转换回证书
- php - Laravel Ubuntu 服务器部署