【问题标题】:frontfill or backfill of STRING column at resample() in pandasPandas 中 resample() 处的 STRING 列的前填充或回填
【发布时间】:2022-11-14 19:19:28
【问题描述】:
在对 ffill() 或 bfill() 对象列进行重采样()时是否有任何方法?
假设我们有:
| Date |
Sort |
Value |
| 2022-10-23 15:40:41 |
A |
1 |
| 2022-10-23 18:43:13 |
B |
2 |
| 2022-10-24 15:40:41 |
C |
3 |
| 2022-10-24 18:43:13 |
D |
4 |
我想得到以下结果:
df.resample("15min").mean()
| Date |
Sort |
Value |
| 2022-10-23 15:45:00 |
A |
1 |
| 2022-10-23 16:00:00 |
A |
1 |
| 2022-10-23 16:15:00 |
A |
1 |
| 2022-10-23 16:35:00 |
A |
1 |
| ... |
... |
... |
| 2022-10-23 18:00:00 |
D |
1 |
| 2022-10-23 18:15:00 |
D |
1 |
| 2022-10-23 18:30:00 |
D |
1 |
| 2022-10-23 18:45:00 |
D |
1 |
但它总是踢出“排序列”。
如果这里有人可以提供帮助,那就太好了!
最好的
米。
【问题讨论】:
标签:
python
pandas
pandas-resample
【解决方案1】:
您可以单独为列指定聚合函数,例如:
df = df.resample("15min").agg({"Sort": min, "Value": np.mean}).ffill()
输出:
Sort Value
Date
2022-10-23 15:30:00 A 1.0
2022-10-23 15:45:00 A 1.0
2022-10-23 16:00:00 A 1.0
2022-10-23 16:15:00 A 1.0
2022-10-23 16:30:00 A 1.0
... ... ...
2022-10-24 17:30:00 C 3.0
2022-10-24 17:45:00 C 3.0
2022-10-24 18:00:00 C 3.0
2022-10-24 18:15:00 C 3.0
2022-10-24 18:30:00 D 4.0
【解决方案2】:
如果需要根据Sort 和mean 每Value 前向填充first valeus,请使用:
df = df.resample("15min").agg({'Sort':'first', 'Value':'mean'}).ffill()
print (df)
Sort Value
Date
2022-10-23 15:30:00 A 1.0
2022-10-23 15:45:00 A 1.0
2022-10-23 16:00:00 A 1.0
2022-10-23 16:15:00 A 1.0
2022-10-23 16:30:00 A 1.0
... ...
2022-10-24 17:30:00 C 3.0
2022-10-24 17:45:00 C 3.0
2022-10-24 18:00:00 C 3.0
2022-10-24 18:15:00 C 3.0
2022-10-24 18:30:00 D 4.0
[109 rows x 2 columns]