熊猫 - 以系列和延迟操作

问题描述 投票:1回答:2

我在Pandas中有以下数据框。我怀疑的是如何在有时间延迟的系列中进行操作。例如,我想计算将一个时期的GDP除以下一个时期的人口的结果。

         GDP     Population
1950     3.31        1
1951     3.5         1
...
2000     15.2        2
python python-3.x pandas
2个回答
3
投票

要做到这一点,你可以使用:

df['new_col'] = df['GDP'] / df['Population'].shift(1)

3
投票

你考虑过使用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
© www.soinside.com 2019 - 2024. All rights reserved.