例如,基于跨多行的其他列创建新列

2024-03-28 11:39:10 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有下面的数据框代表我的宠物青蛙的饮食习惯

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


Tags: 数据宠物todaydate代表nandayspast
1条回答
网友
1楼 · 发布于 2024-03-28 11:39:10

您可以进行滚动求和(使用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()

使用date作为索引并滚动20D(ays)可能更可靠:

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

相关问题 更多 >