gpt4 book ai didi

python - Pandas 石斑鱼 vs 时间石斑鱼

转载 作者:太空狗 更新时间:2023-10-30 02:38:26 27 4
gpt4 key购买 nike

新的 pandas 版本弃用了 TimeGrouper,所以我们应该使用常规的 Grouper

旧代码:

df['column_name'].groupby(pd.TimeGrouper("M")).mean().plot()

在旧版本的 pandas 中运行良好。但是,没有:

df.groupby(pd.Grouper(key='column_name', freq="M")).mean().plot()
df['column_name'].groupby(pd.Grouper(freq="M")).mean().plot()

适用于新版本。要么认为 key 丢失,要么 pandas 提示:

Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Float64Index'

编辑

import pandas as pd

df = pd.DataFrame({'column_name':['2017-01-01', '2017-01-02'],
'column_value':[1,3]})

df

df.index = pd.DatetimeIndex(df.column_name)

df.index

# old version
df['column_value'].groupby(pd.TimeGrouper("M")).mean().plot()

# new version
df.groupby(pd.Grouper(key='column_value', freq="M")).mean().plot()

最佳答案

正如我在评论中所说,key 应该是 grouper 中的 datetime。默认情况下,Timegrouper 会将其转换为日期时间,因此请使用

df['column_name'] = pd.to_datetime(df['column_name'])
# new version
df.groupby(pd.Grouper(key='column_name', freq="M")).mean().plot()

关于python - Pandas 石斑鱼 vs 时间石斑鱼,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47015886/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com