Eu tenho o seguinte dataFrame pandas. É grande dataframe com mais de 500k linhas.
Event_Number Well p_and_s
0 1 7 4.0
1 1 9 0.0
2 1 15 0.0
3 2 7 2.0
4 2 9 7.0
5 2 15 0.0
6 3 5 0.0
7 3 7 8.0
8 3 16 3.0
9 4 7 8.0
10 4 15 0.0
11 5 7 8.0
12 5 9 3.0
13 5 15 6.0
14 6 5 0.0
15 6 7 8.0
16 7 7 8.0
17 7 9 0.0
18 7 15 0.0
19 8 7 8.0
20 8 15 4.0
Eu quero encontrar para cada grupo de [coluna: Event_Number] que [coluna: Well] tem valor maior que 2 na coluna [p_and_s].
O dataFrame final deve ficar assim com uma nova coluna listando todos bem tendo p_and_s maior que 2
Event_Number Well p_and_s well_array
0 1 7 4.0 [7]
1 1 9 0.0 [7]
2 1 15 0.0 [7]
3 2 7 2.0 [9]
4 2 9 7.0 [9]
5 2 15 0.0 [9]
6 3 5 0.0 [7, 16]
7 3 7 8.0 [7, 16]
8 3 16 3.0 [7, 16]
9 4 7 8.0 [7]
10 4 15 0.0 [7]
11 5 7 8.0 [7, 9, 15]
12 5 9 3.0 [7, 9, 15]
13 5 15 6.0 [7, 9, 15]
14 6 5 0.0 [7]
15 6 7 8.0 [7]
16 7 7 8.0 [7]
17 7 9 0.0 [7]
18 7 15 0.0 [7]
19 8 7 8.0 [7, 15]
20 8 15 4.0 [7, 15]
Respostas:
2 para resposta № 1Aqui está um caminho.
s = df[df["p_and_s"] > 2].groupby("Event_Number")["Well"].apply(list)
df["well_array"] = df["Event_Number"].map(s)
Explicação
- Crie um mapeamento de série
Event_Number
paraWell
depois de aplicar um filtro emp_and_s
. - Mapear para o dataframe original por meio de
pd.Series.map
. - Para performance, quando possível
lambda
funções devem ser evitadas, pois representam loops implícitos dispendiosos.
Resultado
Event_Number Well p_and_s well_array
0 1 7 4.0 [7]
1 1 9 0.0 [7]
2 1 15 0.0 [7]
3 2 7 2.0 [9]
4 2 9 7.0 [9]
5 2 15 0.0 [9]
6 3 5 0.0 [7, 16]
7 3 7 8.0 [7, 16]
8 3 16 3.0 [7, 16]
9 4 7 8.0 [7]
10 4 15 0.0 [7]
11 5 7 8.0 [7, 9, 15]
12 5 9 3.0 [7, 9, 15]
13 5 15 6.0 [7, 9, 15]
14 6 5 0.0 [7]
15 6 7 8.0 [7]
16 7 7 8.0 [7]
17 7 9 0.0 [7]
18 7 15 0.0 [7]
19 8 7 8.0 [7, 15]
20 8 15 4.0 [7, 15]
1 para resposta № 2
Você pode tentar isto:
df.groupby("Event_Number")
.apply(lambda x: x.loc[x.p_and_s > 2,"Well"].tolist())
.to_frame(name="well_array")
.merge(df, right_on=["Event_Number"], left_index=True)
Saída:
well_array Event_Number Well p_and_s
0 [7] 1 7 4.0
1 [7] 1 9 0.0
2 [7] 1 15 0.0
3 [9] 2 7 2.0
4 [9] 2 9 7.0
5 [9] 2 15 0.0
6 [7, 16] 3 5 0.0
7 [7, 16] 3 7 8.0
8 [7, 16] 3 16 3.0
9 [7] 4 7 8.0
10 [7] 4 15 0.0
11 [7, 9, 15] 5 7 8.0
12 [7, 9, 15] 5 9 3.0
13 [7, 9, 15] 5 15 6.0
14 [7] 6 5 0.0
15 [7] 6 7 8.0
16 [7] 7 7 8.0
17 [7] 7 9 0.0
18 [7] 7 15 0.0
19 [7, 15] 8 7 8.0
20 [7, 15] 8 15 4.0