web123456

Pandas Exercise 040: The initial value is calculated as 40% change

(Coding Question) There is the following Series, and the change of the value needs to be calculatedpercentageSum value, where the first value is located will be NaN since there is no initial value, please calculate the initial value at 40.

mport pandas as pd

ser = pd.Series([20, 30, 2, 5, 10])
ser
'''
0    20
1    30
2     2
3     5
4    10
dtype: int64
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

The result is:

'''
0    -50.000000
1     50.000000
2    -93.333333
3    150.000000
4    100.000000
dtype: float64
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
The pandas code is as follows:

 ser.pct_change(fill_value=40).mul(100)
'''
0    -50.000000
1     50.000000
2    -93.333333
3    150.000000
4    100.000000
dtype: float64
'''

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Analysis: The fill_value parameter in the pct_change() method is a parameter of the underlying method shift() of pct_change().