9

I have a pandas dataframe in which I want to divide each column by the same data series values for each row. Each column and the data series have the same length. The data series has only float numbers but some cells in the dataframe have NaNs.

I tried various things but somehow I cannot get it solved.

df = df.divide(data_series, axis=1)

Any suggestions? many thanks!

Julia Meshcheryakova
  • 3,162
  • 3
  • 22
  • 42
Rolf12
  • 701
  • 1
  • 6
  • 20

3 Answers3

15

I found the solution: setting axis = 0 solves the issue.

df = df.divide(data_series, axis=0)

many thanks

Julia Meshcheryakova
  • 3,162
  • 3
  • 22
  • 42
Rolf12
  • 701
  • 1
  • 6
  • 20
2

Format your Series index with df columns

df.div(pd.Series([100,100,100],index=df.columns))
Out[132]: 
      A     B    id
0  0.01  0.02  0.01
1  0.02  0.03  0.01
2  0.04  0.00  0.03
3  0.05  0.06  0.01
4  0.08  0.09  0.03
5  0.09  0.07  0.03
BENY
  • 317,841
  • 20
  • 164
  • 234
1

Given dataframe df and series s, you can also use numpy:

res = pd.DataFrame(df.values / s.values[:, None],
                   index=df.index, columns=df.columns)
jpp
  • 159,742
  • 34
  • 281
  • 339