假设您有数据框,并且Id和Age列的前2个值和后2个值之间的百分比变化的结果
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
为了解决这个问题,我们将遵循以下步骤-
定义一个数据框
应用df [['Id','Age']]。pct_change()内部切片[0:2]
df[['Id','Age']].pct_change()[0:2]
应用df [['Id','Age']]。pct_change()内部切片[-2:]
df[['Id','Age']].pct_change()[0:2]
让我们检查以下代码以获得更好的理解-
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:])
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