# Write a Python code to calculate percentage change between Id and Age columns of the top 2 and bottom 2 values

Assume, you have dataframe and the result for percentage change between Id and Age columns top 2 and bottom 2 value

Id and Age-top 2 values
Id Age
0 NaN NaN
1 1.0 0.0
Id and Age-bottom 2 values
Id      Age
3 0.000000 -0.071429
4 0.666667 0.000000

## Solution

To solve this, we will follow the steps given below −

• Define a dataframe

• Apply df[[‘Id’,’Age’]].pct_change() inside slicing [0:2]

df[['Id','Age']].pct_change()[0:2]
• Apply df[[‘Id’,’Age’]].pct_change() inside slicing [-2:]

df[['Id','Age']].pct_change()[0:2]

### Example

Let’s check the following code to get a better understanding −

import pandas as pd
df = pd.DataFrame({"Id":[1, 2, 3, None, 5],
"Age":[12, 12, 14, 13, None],
"Mark":[80, 90, None, 95, 85],
})
print("Dataframe is:\n",df)
print("Id and Age-top 2 values")
print(df[['Id','Age']].pct_change()[0:2])
print("Id and Age-bottom 2 values")
print(df[['Id','Age']].pct_change()[-2:])

### Output

Dataframe is:
Id    Age    Mark
0 1.0   12.0   80.0
1 2.0   12.0   90.0
2 3.0   14.0   NaN
3 NaN   13.0   95.0
4 5.0   NaN    85.0
Id and Age-top 2 values
Id Age
0 NaN NaN
1 1.0 0.0
Id and Age-bottom 2 values
Id      Age
3 0.000000 -0.071429
4 0.666667 0.000000