首页 > 解决方案 > 计算在组中排成一行的值?

问题描述

我有两个数据框:

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。怎么做?

标签: pythonpython-3.xdataframegroup-bycount

解决方案


不是最快的解决方案,但在这里:

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)) ]

推荐阅读