Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

subtract inside DataFrame columns

Would because maybe I did’n sleep this night but, given:

df1 = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'], index=['rank1','rank2','rank3','rank4']}
df2 = {'Age':[28,34,29,42],'bubu':[98,33,3,30], index=['rank1','rank2','rank3','rank4']}
df_merged = = pd.concat([ df1, df2 ], axis = 1)

now, for dynamically manage further arithmetic operation on the columns from a more column dense df:

a = ['Age']  #List
b = ['bubu'] #List

the arithmetic operation:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df_merged['newCol'] = df_merged[a]-df_merged[b]

or both

df_merged.assign(newCol = df_merged[a] - df_merged[b])

I can’t subtract the 2 columns because return such error

ValueError: Expected a 1D array, got an array with shape (556, 2)

>Solution :

Not sure if I understand, but try this:

a = 'Age'
b = 'bubu'

then

df_merged['newCol'] = df_merged[a] - df_merged[b]

produces:

        Name  Age  bubu  newCol
rank1    Tom   28    98     -70
rank2   Jack   34    33       1
rank3  Steve   29     3      26
rank4  Ricky   42    30      12

is that what you were after?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading