sum two columns pandas 1

sum two columns pandas

print(df)
   Apples  Bananas  Grapes  Kiwis
0     2.0      3.0     NaN    1.0
1     1.0      3.0     7.0    NaN
2     NaN      NaN     2.0    3.0

df['Fruit Total']=df.iloc[:,-4:].sum(axis=1)

print(df)
   Apples  Bananas  Grapes  Kiwis  Fruit Total
0     2.0      3.0     NaN    1.0          6.0
1     1.0      3.0     7.0    NaN         11.0
2     NaN      NaN     2.0    3.0          5.0

Here is what the above code is Doing:
1. We create a new column called ‘Fruit Total’
2. We use the .iloc[] method to select the last 4 columns of the dataframe
3. We use the .sum() method to sum the values of the last 4 columns
4. We use the .sum(axis=1) method to sum the values of the last 4 columns by row
5. We assign the sum of the last 4 columns to the ‘Fruit Total’ column

Similar Posts