0

I am trying to divide one column in a dataframe by a number while bringing back all other columns in a dataframe unchanged. The code below works for the division, but I dont know how to bring back the columns I wanted unchanged from the dataframe as well:

df= df[['C']].div(4, axis = 0)

the data looks like this

enter image description here

The output that I am looking for would be:

enter image description here

The closest I could find to an answer is here:Divide multiple columns by another column in pandas

However, the last quote says to use pd.set_index after the division, but I am not sure how that syntax is supposed to look.

Right now I am only getting the output column C not the two other columns.

burnsa9
  • 131
  • 2
  • 3
  • 10

1 Answers1

2

You can do:

df['C']= df['C']/4

It will divide the column C by 4 while keeping other columns same.

You are getting the output column C only because you are saving column C changed only:

df['C']= df[['C']].div(4, axis=0)

This may give you the exact result

Kyle
  • 2,814
  • 2
  • 17
  • 30
Vikika
  • 318
  • 1
  • 9
  • When I go to Print df it is still only showing the division output, not the other columns A and B. – burnsa9 Nov 30 '18 at 19:54
  • Have you used df['C']= df['C']/4 . It should give you the desired output. Can you share the whole code. – Vikika Nov 30 '18 at 19:57
  • new_df = df['C'] = df[['C']].div(4, axis=0) print(new_df) – burnsa9 Nov 30 '18 at 20:02
  • 1
    Dude. You are doing it in a wrong way. You are changing the column C with this df[['C']].div(4, axis=0) and the you are storing it into new_df. So only column 'C' will get changed and stored. By doing df['C']= df['C']/4 only C column will get changed. Then you can print df. It will show you the changes. – Vikika Nov 30 '18 at 20:05