1

How do i create a new column by subtracting "Build" from "Build Dep" and "Car" from "Car Dep" without it only filling in all values with just one number?

Below is dataframe I was using.

df = pd.DataFrame({'Accounts':['Cash','Build','Build Dep', 'Car', 'Car Dep'],
              'Debits':[300,500,0,100,0],
              'Credits':[0,0,250,0,50]})

df
Richard
  • 15
  • 1
  • 2
  • 5

2 Answers2

1

Simple as using the - operator on columns.

df['Net'] = df['Credits'] - df['Debits']
fawcj001
  • 64
  • 4
1

It looks like you want to create new rows. You can index the dataframe by Account which also has the advantage that the remaining columns are the things you want to subtract. Then subtract and add a new row.

>>> df = pd.DataFrame({'Accounts':['Cash','Build','Build Dep', 'Car', 'Car Dep'],
...               'Debits':[300,500,0,100,0],
...               'Credits':[0,0,250,0,50]})
>>> 
>>> df = df.set_index('Accounts')
>>> df.loc['Build Delta'] = df.loc['Build Dep'] - df.loc['Build']
>>> df.loc['Car Delta'] = df.loc['Car'] - df.loc['Car Dep']
>>> 
>>> print(df)
             Debits  Credits
Accounts                    
Cash            300        0
Build           500        0
Build Dep         0      250
Car             100        0
Car Dep           0       50
Build Delta    -500      250
Car Delta       100      -50

If you want to have a column of deltas for all of the rows, just subtract the columns. This is the beauty of numpy and pandas. You can apply operations to entire columns with small amounts of code and get better performance than if you did it in vanilla python.

>>> df = pd.DataFrame({'Accounts':['Cash','Build','Build Dep', 'Car', 'Car Dep'],
...               'Debits':[300,500,0,100,0],
...               'Credits':[0,0,250,0,50]})
>>> 
>>> df = df.set_index('Accounts')
>>> 
>>> 
>>> 
>>> df['Delta'] = df['Credits'] - df['Debits']
>>> df
           Debits  Credits  Delta
Accounts                         
Cash          300        0   -300
Build         500        0   -500
Build Dep       0      250    250
Car           100        0   -100
Car Dep         0       50     50
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • Thank you for your help! Is there a way for me to do the same thing but add a new column with all the Deltas in one column? – Richard Jun 17 '20 at 00:37
  • Yes, and its @fawcj001's answer. Its the more normal way to do pandas - operations on entire columns. I'll include an example but if its the way you want to go, I suggest moving your accept to fawcj001 so others will know you think its the right way to go. – tdelaney Jun 17 '20 at 00:47