Home > Software engineering >  subtract inside DataFrame columns
subtract inside DataFrame columns

Time:02-10

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:

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)

CodePudding user response:

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?

CodePudding user response:

df_merged['newCol'] = df_merged['Age']-df_merged['bubu'] or
df_merged.insert(3,'newCol', df_merged['Age']-df_merged['bubu'],True)
  • Related