python Pandas Dataframe 组按日期时间月

ruyhziif  于 2022-12-21  发布在  Python
关注(0)|答案(5)|浏览(123)

考虑CSV文件:

string,date,number
a string,2/5/11 9:16am,1.0
a string,3/5/11 10:44pm,2.0
a string,4/22/11 12:07pm,3.0
a string,4/22/11 12:10pm,4.0
a string,4/29/11 11:59am,1.0
a string,5/2/11 1:41pm,2.0
a string,5/2/11 2:02pm,3.0
a string,5/2/11 2:56pm,4.0
a string,5/2/11 3:00pm,5.0
a string,5/2/14 3:02pm,6.0
a string,5/2/14 3:18pm,7.0

我可以读取此内容,并将日期列重新格式化为日期时间格式:

b = pd.read_csv('b.dat')
b['date'] = pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')

我一直在尝试按月对数据进行分组。似乎应该有一种明显的方法来访问月份并按此分组。但我似乎无法做到这一点。有人知道如何做到这一点吗?
我正在尝试按日期重新编制索引:

b.index = b['date']

我可以这样访问月份:

b.index.month

然而,我似乎找不到一个函数来按月汇总。

g2ieeal7

g2ieeal71#

成功做到了:

b = pd.read_csv('b.dat')
b.index = pd.to_datetime(b['date'],format='%m/%d/%y %I:%M%p')
b.groupby(by=[b.index.month, b.index.year])

或者

b.groupby(pd.Grouper(freq='M'))  # update for v0.21+
7gcisfzg

7gcisfzg2#

(更新日期:2018年)

请注意,pd.Timegrouper已折旧并将被删除。请改用:

df.groupby(pd.Grouper(freq='M'))
nxagd54h

nxagd54h3#

要按时间序列数据进行groupby,可以使用方法resample。例如,要按月份进行groupby:

df.resample(rule='M', on='date')['Values'].sum()

您可以在此处找到偏移别名列表。

t9aqgxwy

t9aqgxwy4#

避免MultiIndex的一个解决方案是创建一个新的datetime列,设置day = 1,然后按此列分组。

正常化每月的日期

df = pd.DataFrame({'Date': pd.to_datetime(['2017-10-05', '2017-10-20', '2017-10-01', '2017-09-01']),
                   'Values': [5, 10, 15, 20]})

# normalize day to beginning of month, 4 alternative methods below
df['YearMonth'] = df['Date'] + pd.offsets.MonthEnd(-1) + pd.offsets.Day(1)
df['YearMonth'] = df['Date'] - pd.to_timedelta(df['Date'].dt.day-1, unit='D')
df['YearMonth'] = df['Date'].map(lambda dt: dt.replace(day=1))
df['YearMonth'] = df['Date'].dt.normalize().map(pd.tseries.offsets.MonthBegin().rollback)

然后正常使用groupby

g = df.groupby('YearMonth')

res = g['Values'].sum()

# YearMonth
# 2017-09-01    20
# 2017-10-01    30
# Name: Values, dtype: int64

pd.Grouper的比较

pd.Grouper不同的是,这种解决方案的微妙好处是grouper索引被标准化为每个月的 * 开始 * 而不是结束,因此您可以通过get_group轻松地提取组:

some_group = g.get_group('2017-10-01')

计算10月的最后一天稍微麻烦一些。pd.Grouper,从v0.23开始,确实支持convention参数,但这只适用于PeriodIndex石斑鱼。

与字符串转换比较

上述方法的替代方法是转换为字符串,例如将datetime 2017-10-XX转换为string '2017-10'。但是,不建议这样做,因为与object字符串系列(存储为指针数组)相比,datetime系列(存储为内部连续内存块中的数值数据)的效率优势将全部丧失。

smdnsysy

smdnsysy5#

与@jpp的解决方案略有不同,但输出的是YearMonth字符串:

df['YearMonth'] = pd.to_datetime(df['Date']).apply(lambda x: '{year}-{month}'.format(year=x.year, month=x.month))

res = df.groupby('YearMonth')['Values'].sum()

相关问题