python - 熊猫:resample.apply 丢弃索引名称
问题描述
出于某种原因,df.resample("M").apply(foo)
将索引名称放在df
. 这是预期的行为吗?
import pandas as pd
df = pd.DataFrame({"a": np.arange(60)}, index=pd.date_range(start="2018-01-01", periods=60))
df.index.name = "dte"
df.head()
# a
#dte
#2018-01-01 0
#2018-01-02 1
#2018-01-03 2
#2018-01-04 3
#2018-01-05 4
def f(x):
print(x.head())
df.resample("M").apply(f)
#2018-01-01 0
#2018-01-02 1
#2018-01-03 2
#2018-01-04 3
#2018-01-05 4
#Name: a, dtype: int64
更新/澄清: 当我说删除名称时,我的意思是函数接收到的系列没有与其索引关联的名称组件
解决方案
我建议使用resample
- groupby
with的替代方法Grouper
:
def f(x):
print(x.head())
df.groupby(pd.Grouper(freq="M")).apply(f)
dte
2018-01-01 0
2018-01-02 1
2018-01-03 2
2018-01-04 3
2018-01-05 4
a
dte
2018-01-01 0
2018-01-02 1
2018-01-03 2
2018-01-04 3
2018-01-05 4
a
dte
2018-02-01 31
2018-02-02 32
2018-02-03 33
2018-02-04 34
2018-02-05 35
推荐阅读
- go - 允许超过 content-type: application/json in gorilla
- java - 没有约束异常处理的休眠线程安全幂等插入?
- amazon-web-services - 使用 Route53、带缓存的 CloudFront、ELB 将 APEX 域重定向到子域
- r - R data.table 外连接与 roll="nearest" 有约束
- python - 迭代我的值的 2 个模型之间的 Django Queryset 过滤器对象?
- javascript - 为什么父自定义元素方法被覆盖?
- rundeck - 如何在脚本中访问 Rundeck Job 执行编号?
- node.js - 如何从谷歌云获取 Nodejs 源代码
- r - 如何修复在ggplot2中制作的动态图?
- mongodb - 如何通过模型、服务和控制器使用 springboot 进行 crud 操作