将pandas时间戳转换为月末

时间:2017-07-08 17:47:03

标签: python pandas date timestamp date-formatting

我有以下代码:

#!/usr/bin/python

import pandas as pd

df = pd.read_excel(io='http://www.iea.org/gtf/download/Export_GTF_IEA.xls', sheetname='Data', skip_footer=5, )

df = df.drop('Unnamed: 2', axis=1)
df = df.drop('Exit', axis=1)
df = df.drop('Entry', axis=1)
df = df.drop('MAXFLOW (Mm3/h)', axis=1)

df = df.T

df.to_csv('foo.csv', encoding='utf-8', sep='\t', header=False)

输出样本如下所示:

print df
                              0        1           2           3        4    \
Borderpoint          Adriatic LNG  Almeria  Alveringem  Alveringem  Badajoz   
2008-10-01 00:00:00             0        0           0           0   152.81   
2008-11-01 00:00:00             0        0           0           0   183.31   
2008-12-01 00:00:00             0        0           0           0    85.21   
2009-01-01 00:00:00             0        0           0           0   199.16   
2009-02-01 00:00:00             0        0           0           0   104.48   
2009-03-01 00:00:00             0        0           0           0     9.17   

如何将时间戳转换为月末日期?

1 个答案:

答案 0 :(得分:2)

未正确设置标头,以便设置可以使用的正确标头

df.columns = df.iloc[0]
df.drop(df.index[:1], inplace=True)

Den将时间戳更改为您可以使用的月结束日期

df.index = df.index + pd.offsets.MonthEnd(0)

输出:

Borderpoint Adriatic LNG  Almeria Alveringem Alveringem  Badajoz Badajoz  
2008-10-31             0        0          0          0   152.81       0   
2008-11-30             0        0          0          0   183.31       0   
2008-12-31             0        0          0          0    85.21       0   
2009-01-31             0        0          0          0   199.16       0   
2009-02-28             0        0          0          0   104.48      12   
2009-03-31             0        0          0          0     9.17       2   
2009-04-30             0        0          0          0   190.49       0   
2009-05-31             0        0          0          0        0       0