0

I'm looking to do the following calculation in a way that prevents a warning error from python:

My table has the following example data setup for one row:

a b c d e f g

5 2 4 3 1 2 5

df['d'] = ((df['d']/df['c']))*100

As you can see, I'm looking to overwrite column 'xxx' with the new calculated figure. I can do it as above no issue but python recommends using loc and I can't get the syntax right.

I'd be looking for (3/4)*100 = 750

a b c  d  e f g

5 2 4 750 1 2 5
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
AndrewK
  • 27
  • 6

1 Answers1

0

I used .iloc to solve this problem.

I recreated your data frame over here -

import numpy as np
import pandas as pd
data = {'a':[5,2],'b':[2,3],'c':[4,4],'d':[3,5],'e':[1,2],'f':[2,3],'g':[5,6]}
df = pd.DataFrame(data)
df

   a    b   c   d   e   f   g
0   5   2   4   3   1   2   5
1   2   3   4   5   2   3   6

Here is the division -

df.loc['d'] = ((df.iloc[:,3]/df.iloc[:,2]))*100
df

   a    b   c   d   e   f   g
0   5   2   4   75.0    1   2   5
1   2   3   4   125.0   2   3   6

I hope this solves your problem

desert_ranger
  • 1,096
  • 3
  • 13
  • 26
  • Thank you. For some reason I still get the following error: C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead – AndrewK Jun 05 '20 at 01:32
  • @AndrewK, does this modification help you - df.loc['d'] = ((df.iloc[:,3]/df.iloc[:,2]))*100 – desert_ranger Jun 05 '20 at 02:24