简体   繁体   中英

Pandas how do I prevent myself from iterating through rows?

I have the following dataframe

Charge_type Amount Quantity
Credit        2.5    3 
Credit        3.24   2
Debit         5.98   6

I need the following output, if Charge_type is a 'credit' then multiply 'Amount' * -1 and 'Quantity' * -1 to get the following result:

Charge_type Amount Quantity
Credit       -2.5    -3 
Credit       -3.24   -2
Debit         5.98    6

I have no idea where to begin, everywhere I looked online says not to iterate in pandas. Sorry I'm still such a beginner with Python and Pandas. Any help is appreciated.

One option is to use loc :

df.loc[df['Charge_type'].eq('Credit'), ['Amount', 'Quantity']] *= -1

The first part creates a Boolean index df['Charge_type'].eq('Credit') (to select rows based on where Charge_type is 'Credit').

The second part choses the columns to affect ['Amount', 'Quantity'] in this case, 'Amount' and 'Quantity'.

Lastly, mutate using the shortcut operator *= to negate the values.

df :

  Charge_type  Amount  Quantity
0      Credit   -2.50        -3
1      Credit   -3.24        -2
2       Debit    5.98         6

You can create a masking for the column Charge_type , and use .loc along with column name to access the column where the masking has True value, and then assign the new value accordingly:

mask = df['Charge_type'] == 'Credit'
df.loc[mask, 'Amount'] = -df['Amount']
df.loc[mask, 'Quantity'] = -df['Quantity']

OUTPUT :

  Charge_type  Amount  Quantity
0      Credit   -2.50        -3
1      Credit   -3.24        -2
2       Debit    5.98         6

I think combining the approaches from the other two answers (already upvoted both) is most readable:

mask = df['Charge_type'] == 'Credit'
df.loc[mask, ['Amount', 'Quantity']] *= -1

Output:

  Charge_type  Amount  Quantity
0      Credit   -2.50        -3
1      Credit   -3.24        -2
2       Debit    5.98         6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM