Question: I have one array that I am trying to combine all the sub values that have the same key name and add an extra if there is only 2 with the same key name.

her is a saml example of the array this array hase 92 rows

```
Array
(
    [0] => Array ( 
            [N_127y4Gral] => Array ( 
                    [0] => 302
                )
        )
    [1] => Array ( 
            [N_127y4Gral] => Array ( 
                    [0] => 288
                )
        )
    [2] => Array ( 
            [N_144y4Gral] => Array ( 
                    [0] => 317
                )
        )
    [3] => Array ( 
            [N_144y4Gral] => Array ( 
                    [0] => 307
                )
        )
    [4] => Array ( 
            [N_144y4Gral] => Array ( 
                    [0] => 332
                )
        )
)

```

and this is the output I am looking for.

```
Array
(
    [0] => Array ( 
            [N_127y4Gral] => Array ( 
                    [0] => 302
                    [1] => 288
                    [2] => 0
                )
        )
    [1] => Array ( 
            [N_144y4Gral] => Array ( 
                    [0] => 317
                    [1] => 307
                    [2] => 332
                )
        )
)

```

I think i need to use a foreach or for loop to make this happen but i'm not sure on how to structure the function, any suggestion is greatly appreciated.

Answer: 
You can use something like this:

```
my_list = list(df.groupby('CHAMADO').apply(lambda x: x[:3][x[:3]['VALOR_NEW'].str.contains('Contrato',na=False)])['CHAMADO'].values)
#[2019000518, 2019000523, 2019000524]

```

This gives a list of the group which contains the word `Contrato` in the first 3 rows.

```
>>df[df.CHAMADO.isin(my_list)]

```

This will give you the entire dataframe containing those values under `CHAMADO` which has `Contrato` in the first 3 lines. 

For storing the values in separate dataframes you can create a dictionary:

```
dfs = ['df_' + str(x) for x in my_list]
dicdf = dict()
i = 0 
while i < len(dfs):
    dicdf[dfs[i]] = df[(df['CHAMADO']== my_list[i])]
    i = i + 1
print(dicdf)

```

You can store via any other methods you like or see in SO.
IIUC, you need to check your grouped dataframes for `'Contrato'` in the `'VALOR_NEW'` column within the first three rows. This check should do it:

```
if (group['VALOR_NEW'].head(3) == 'Contrato').any():
    print(group)

```