python - 当满足时间序列的条件时,Python Pandas 会聚合过去的行
问题描述
我有一个时间序列问题,我想根据某个列中出现的值聚合一些数据。为了说明,请考虑下表
日期 | 可乐 | colB | 科尔C |
---|---|---|---|
2019-01-01 | 1 | -10 | 无效的 |
2019-01-02 | 2 | -5 | 无效的 |
2019-01-03 | 3 | 0 | 101 |
2019-01-04 | 4 | 5 | 101 |
2019-01-05 | 5 | 10 | 101 |
2019-01-06 | 6 | 15 | 无效的 |
2019-01-07 | 7 | 20 | 101 |
我想完成以下任务:
- 当 colC 的值不为空时,将值聚合到该行并获取日期列的增量
- 如果 colC 的元素 X 不为空,但元素 (X-1) 也不为空,则忽略行 X。
对于上一个表,结果将是
聚合(colC) | 平均(colA) | 平均(colB) | delta(日期)[以天为单位] |
---|---|---|---|
101 | 2 | -5 | 2 |
101 | 6.5 | 17.5 | 1 |
到目前为止,我找不到任何方法来实现这一点
解决方案
尝试groupby
:
#convert Date column to datetime if needed
df["Date"] = pd.to_datetime(df["Date"])
#keep only rows where there aren't consecutive non-null values
df2 = df[~(df["colC"].notnull()&df["colC"].shift().notnull())]
#groupby consecutive null values and aggregate
output = df2.groupby(df2["colC"].notnull().shift().cumsum().fillna(0)) \
.agg({"colA": "mean", \
"colB": "mean", \
"colC": "first", \
"Date": lambda x: (x.max()-x.min()).days}) \
.rename_axis(None) \
.rename(columns={"Date": "Delta"})
>>> output
colA colB colC Delta
0.0 2.0 -5.0 101.0 2
1.0 6.5 17.5 101.0 1
推荐阅读
- html - 边框半径圆圈没有滑到屏幕中间
- botframework - 在 LUIS(Azure 认知服务)中设置警报以跟踪用户活动
- airflow - Airflow - bigquery 运算符中的 xcom_pull
- bash - 使用 ffmpeg 重新流式传输 youtube 视频
- django - 我想使用 Django 上传多个文件
- symfony - Sylius 资源和学说过滤器
- python - ImageDataGenerator 的配置 - 每个字符一个热编码标签
- .net-core - .net core Windows Service Wix install Window service 问题:要执行的应用程序不存在
- alfresco - 在露天的 aikau 小部件中覆盖函数的最佳方法是什么?
- java - 如何在 Java Android Studio 中阅读 .pickle?