相关疑难解决方法(0)

Pandas - 将数据帧多索引转换为datetime对象

考虑一个输入文件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
Run Code Online (Sandbox Code Playgroud)

我可以像这样分组每月总数:

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()
Run Code Online (Sandbox Code Playgroud)

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

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]])
Run Code Online (Sandbox Code Playgroud)

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

我尝试过以下方法:

bgs.index = …
Run Code Online (Sandbox Code Playgroud)

python pandas

5
推荐指数
1
解决办法
2951
查看次数

标签 统计

pandas ×1

python ×1