es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Cómo crear una columna para ‘número de wickets’

Este es el resultado para la tabla anterior:


{'batfast_id': {0: 'bfs1',
1: 'bfs1',
2: 'bfs1',
3: 'bfs1',
4: 'bfs1',
5: 'bfs1',
6: 'bfs1',
7: 'bfs2',
8: 'bfs2',
9: 'bfs2',
10: 'bfs2',
11: 'bfs2',
12: 'bfs2'},
'score': {0: 1,
1: 2,
2: 0,
3: 0,
4: 1,
5: 0,
6: 3,
7: 3,
8: 0,
9: 0,
10: 2,
11: 2,
12: 0},
'day_month_year': {0: '01-01-2020',
1: '01-01-2020',
2: '01-01-2020',
3: '01-01-2020',
4: '02-01-2020',
5: '02-01-2020',
6: '02-01-2020',
7: '02-01-2020',
8: '02-01-2020',
9: '02-01-2020',
10: '03-01-2020',
11: '03-01-2020',
12: '03-01-2020'},
'runs': {0: 1,
1: 3,
2: 3,
3: 3,
4: 1,
5: 1,
6: 4,
7: 3,
8: 3,
9: 3,
10: 2,
11: 4,
12: 4},
'deliveries_faced': {0: 1,
1: 2,
2: 3,
3: 4,
4: 1,
5: 2,
6: 3,
7: 1,
8: 2,
9: 3,
10: 1,
11: 2,
12: 3},
'wicket': {0: 'Not Out',
1: 'Not Out',
2: 'Bowled',
3: 'Caught',
4: 'Not Out',
5: 'Caught',
6: 'Not Out',
7: 'Not Out',
8: 'Bowled',
9: 'Bowled',
10: 'Not Out',
11: 'Not Out',
12: 'Caught'},
'no_of_wickets': {0: 0,
1: 0,
2: 1,
3: 2,
4: 0,
5: 1,
6: 1,
7: 0,
8: 1,
9: 2,
10: 0,
11: 0,
12: 1}}

Estoy tratando de crear una columna llamada no_of_wickets que cuente cuántos wickets ha perdido el usuario jugando cricket. Sin embargo, debe restablecerse a 0 cuando cambie la fecha o batfast_id (el usuario).

El score es el número de carreras que el jugador recibió en ese lanzamiento y el runs es el número acumulativo del score.

El código utilizado para crear runs es: df['runs']=df.groupby(['batfast_id','day_month_year'])['score'].cumsum()

El código utilizado para crear deliveries_faced es: df['deliveries_faced']=df.groupby(['batfast_id','day_month_year']).cumcount()+1

Tags:  , , ,

Answer

  1. Avatar for davy.ai

    Para crear la columna no_of_wickets que se reinicia a 0 cuando la fecha o batfast_id cambian, podemos utilizar la función groupby y el método cumsum() para contar el número de wickets para cada grupo de batfast_id y day_month_year. También utilizaremos el método shift() para verificar cuando el valor de la columna wicket cambia de “Not Out” a “Bowled” o “Caught”.

    Aquí está el código para crear la columna no_of_wickets:

    # crear una máscara cuando se pierden wickets
    mask = (df['wicket'] != "Not Out") & (df['wicket'].shift(1) == "Not Out")
    
    # agrupar por batfast_id y day_month_year, y aplicar la suma acumulativa y reiniciar los wickets cuando sea necesario
    df['no_of_wickets'] = df.groupby([(df['batfast_id'] != df['batfast_id'].shift(1)), df['batfast_id'], df['day_month_year']])[mask].cumsum()
    

    La columna resultante no_of_wickets tendrá el recuento de wickets para cada grupo y se reiniciará a 0 cuando cambie tanto el batfast_id como el day_month_year.

Comments are closed.