Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy conditional values from one column to another

Tags:

python

pandas

Given a df like this:

Date          Category  Debit     Credit
2020-01-05    Utility   55.32     NA
2020-01-05    Movie     20.01     NA
2020-01-05    Payment   NA        -255.32
2020-01-05    Grocery   97.64     NA

How do I move all negative Credit values to the Debit column (and delete the empty Credit column)?

Date          Category  Debit     
2020-01-05    Utility   55.32    
2020-01-05    Movie     20.01    
2020-01-05    Payment   -255.32        
2020-01-05    Grocery   97.64    

This will find the negative values:

df.loc[df['Credit'] < 0]

But this doesn't work (minimal pandas skills)

def creditmover():
    If df.loc[df['Credit'] < 0]:
        df.loc[df['Debit']]=df.loc[df['Credit']]

Thanks!

like image 407
CLS Avatar asked Jan 26 '23 00:01

CLS


2 Answers

We can do pop

df.loc[df.pop('Credit')<=0,'Debit']=df.Credit
df
         Date Category   Debit
0  2020-01-05  Utility   55.32
1  2020-01-05    Movie   20.01
2  2020-01-05  Payment -255.32
3  2020-01-05  Grocery   97.64
like image 176
BENY Avatar answered Jan 28 '23 11:01

BENY


According to your logic, you could do:

# where credit is < 0
s = df['Credit'] < 0

# copy the corresponding values
df.loc[s, 'Debit'] = df.loc[s, 'Credit']

# drop Credit
df = df.drop('Credit', axis=1)

Output:

         Date Category   Debit
0  2020-01-05  Utility   55.32
1  2020-01-05    Movie   20.01
2  2020-01-05  Payment -255.32
3  2020-01-05  Grocery   97.64

Note: If Debit is always Na wherever Credit is <0 and vise versa, then you can simply do:

df['Debit'] = df['Debit'].fillna(df['Credit'])

df = df.drop('Credit', axis=1)
like image 33
Quang Hoang Avatar answered Jan 28 '23 12:01

Quang Hoang