熊猫,根据多行中的其他列创建新列

时间:2019-02-06 04:17:19

标签: python pandas

让我们说以下数据框代表了我的宠物青蛙的饮食习惯

date       bugs_eaten_today
2019-01-31 0
2019-01-30 5
2019-01-29 6
2019-01-28 7
2019-01-27 2
...

现在我要计算一个新列bugs_eaten_past_20_days

date       bugs_eaten_today bugs_eaten_paast_20_days
2019-01-31 0                48
2019-01-30 5                38
2019-01-29 6                57
2019-01-28 7                63
2019-01-27 2                21
...

我将如何去做? (请注意,我们没有最后20行的数据,因此它们仅为NaN

1 个答案:

答案 0 :(得分:1)

您可以进行累加计算(用20而不是3):

In [11]: df.bugs_eaten_today.rolling(3, 1).sum()
Out[11]:
0     0.0
1     5.0
2    11.0
3    18.0
4    15.0
Name: bugs_eaten_today, dtype: float64

您必须反向执行此操作,因为索引是反向的:

In [12]: df[::-1].bugs_eaten_today.rolling(3, 1).sum()
Out[12]:
4     2.0
3     9.0
2    15.0
1    18.0
0    11.0
Name: bugs_eaten_today, dtype: float64

In [13]: df['bugs_eaten_paast_20_days'] = df[::-1].bugs_eaten_today.rolling(3, 1).sum()

使用日期作为索引并翻转20天(可能)会更健壮:

In [21]: df1 = df.set_index('date').sort_index()

In [22]: df1.bugs_eaten_today.rolling('3D', 1).sum()
Out[22]:
date
2019-01-27     2.0
2019-01-28     9.0
2019-01-29    15.0
2019-01-30    18.0
2019-01-31    11.0
Name: bugs_eaten_today, dtype: float64
相关问题