我在Pandas中有以下数据框。我怀疑的是如何在有时间延迟的系列中进行操作。例如,我想计算将一个时期的GDP除以下一个时期的人口的结果。
GDP Population
1950 3.31 1
1951 3.5 1
...
2000 15.2 2
要做到这一点,你可以使用:
df['new_col'] = df['GDP'] / df['Population'].shift(1)
你考虑过使用shift
吗?
import pandas as pd
import numpy as np
df = pd.DataFrame({"GDP": np.random.normal(3,1,51),
"Pop":np.random.randint(1,10,51)},
index=np.arange(1950,2001))
df["res"] = df.GDP.shift(1)/df.Pop