Zanthoxylum piperitum:
Tengo df con nombre tiene tres columnas, la cantidad y el tipo. Estoy intentando añadir o valores subract al usuario en función del tipo de
Aquí está mi df muestra
name amount type
0 John 10 ADD
1 John 20 ADD
2 John 50 ADD
3 John 50 SUBRACT
4 Adam 15 ADD
5 Adam 25 ADD
6 Adam 5 ADD
7 Adam 30 SUBRACT
8 Mary 100 ADD
Mi df resultante
name amount
0 John 30
1 Adam 15
2 Mary 100
Jezreel:
Idea es múltiple por 1
si ADD
y -1
si SUBRACT
la columna y luego agregada sum
:
df1 = (df['amount'].mul(df['type'].map({'ADD':1, 'SUBRACT':-1}))
.groupby(df['name'], sort=False)
.sum()
.reset_index(name='amount'))
print (df1)
name amount
0 John 30
1 Adam 15
2 Mary 100
detalle :
print (df['type'].map({'ADD':1, 'SUBRACT':-1}))
0 1
1 1
2 1
3 -1
4 1
5 1
6 1
7 -1
8 1
Name: type, dtype: int64
También es posible especificar valores negativos únicamente con numpy.where
de múltiples por -1
y toda otra por 1
:
df1 = (df['amount'].mul(np.where(df['type'].eq('SUBRACT'), -1, 1))
.groupby(df['name'], sort=False)
.sum()
.reset_index(name='amount'))
print (df1)
name amount
0 John 30
1 Adam 15
2 Mary 100