gpt4 book ai didi

python - Pandas - 将数据帧多索引转换为日期时间对象

转载 作者:太空狗 更新时间:2023-10-30 00:44:54 26 4
gpt4 key购买 nike

考虑一个输入文件,b.dat:

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']
bg=pd.groupby(b,by=[b.index.year,b.index.month])
bgs=bg.sum()

分组总数的索引如下所示:

bgs

number
2011 2 1
3 2
4 8
5 14
2014 5 13

bgs.index

MultiIndex(levels=[[2011, 2014], [2, 3, 4, 5]],
labels=[[0, 0, 0, 0, 1], [0, 1, 2, 3, 3]])

我想将索引重新格式化为日期时间格式(天数可以是一个月的第一天)。

我试过以下方法:

bgs.index = pd.to_datetime(bgs.index)

bgs.index = pd.DatetimeIndex(bgs.index)

两者都失败了。有谁知道我该怎么做?

最佳答案

考虑 resample按“M”而不是按 DatetimeIndex 的属性分组:

In [11]: b.resample('M', how='sum').dropna()
Out[11]:
number
date
2011-02-28 1
2011-03-31 2
2011-04-30 8
2011-05-31 14
2014-05-31 13

注意:如果您不想要中间的月份,则必须删除 NaN。

关于python - Pandas - 将数据帧多索引转换为日期时间对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24090710/

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