vsoler vsoler - 2 months ago 10
Python Question

Selecting the values of the first row in pandas' DataFrame

I have the following DataFrame

AAPL F IBM
Date
2016-05-02 46.536664 13.62 143.881476
2016-05-03 47.302004 13.43 142.752373
2016-05-04 46.810001 13.31 142.871221
2016-05-05 46.619999 13.32 145.070003
2016-05-06 46.360000 13.44 147.289993


I´d like to divide each column by the value of the first row and the multiply by 100. After the calculation, the first 2 rows should look like this:

AAPL F IBM
Date
2016-05-02 100 100 100
2016-05-03 101.63 98.60 99.21


I'm struggling, but I can't get it. Any help appreciated

Answer

try something like this:

df /= df.iloc[0]/100

or

df = df.apply(lambda x: x/x.iloc[0]*100)

Test:

In [51]: df
Out[51]:
                 AAPL      F         IBM
Date
2016-05-02  46.536664  13.62  143.881476
2016-05-03  47.302004  13.43  142.752373
2016-05-04  46.810001  13.31  142.871221
2016-05-05  46.619999  13.32  145.070003
2016-05-06  46.360000  13.44  147.289993

Output:

In [63]: df /= df.iloc[0]/100

In [64]: df
Out[64]:
                  AAPL           F         IBM
Date
2016-05-02  100.000000  100.000000  100.000000
2016-05-03  101.644596   98.604993   99.215255
2016-05-04  100.587358   97.723935   99.297856
2016-05-05  100.179074   97.797357  100.826046
2016-05-06   99.620377   98.678414  102.368976
Comments