pandas groupby 申请永远

pandas groupby apply is taking forever

我正在尝试通过 5 次不同的采访(变量 V1016)识别大型数据框中的个人,并将其存储在变量 KeyInd 中。 KeyDomnascimento 具有相同值的行属于同一个人。

这是数据帧的示例:

V1016 V2009 V2007 keyDom keyInd nascimento
1 64 1 11000003417 0 1 - 7/11/1953
1 37 2 11000003417 0 2 - 22/12/1980
1 14 2 11000003417 0 2 - 1/11/2003
2 64 1 11000003417 0 1 - 7/11/1953
2 37 2 11000003417 0 2 - 22/12/1980
2 14 2 11000003417 0 2 - 1/11/2003
3 65 1 11000003417 0 1 - 7/11/1953
3 37 2 11000003417 0 2 - 22/12/1980
3 15 2 11000003417 0 2 - 1/11/2003

我正在尝试使用 groupby.apply:

传递此函数
def identifica_pessoas(df):
    pessoas = df[df['V1016'] == 1]['nascimento'].tolist()
    rodadas = list(range(1, 6))
    for rodada in rodadas:
        row = df[df.V1016 == rodada]
        for i in range(len(pessoas)):
            try:
                indice = [index for index, value in enumerate(pessoas) if value == row.nascimento.iloc[i]][0]
                row.keyInd.iloc[i] = row.keyDom.iloc[i] + str(indice)
            except:
                pass
        df[df.V1016 == rodada] = row
    return df

传递函数的代码如下:

painel7_filtrado = painel7.groupby('keyDom').apply(identifica_pessoas)

我期待的结果是这样的:

V1016 V2009 V2007 keyDom keyInd nascimento
1 64 1 11000003417 110000034170 1 - 7/11/1953
1 37 2 11000003417 110000034171 2 - 22/12/1980
1 14 2 11000003417 110000034172 2 - 1/11/2003
2 64 1 11000003417 110000034170 1 - 7/11/1953
2 37 2 11000003417 110000034171 2 - 22/12/1980
2 14 2 11000003417 110000034172 2 - 1/11/2003
3 65 1 11000003417 110000034170 1 - 7/11/1953
3 37 2 11000003417 110000034171 2 - 22/12/1980
3 15 2 11000003417 110000034172 2 - 1/11/2003

但是处理需要几个小时。我怎样才能使这段代码更快?

我用不同的方法解决了这个问题。我在第一次采访中用一个 ID 创建了另一个数据框,而不是我对主数据框使用 merge。工作得很好。