【问题标题】:Convert pandas timestamp to month endate将熊猫时间戳转换为月末日期
【发布时间】:2017-12-12 20:01:09
【问题描述】:

我有以下代码:

#!/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   

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

【问题讨论】:

  • 在您的示例输出中,Borderpoint 列日期是每个月的第一个日期(不是最后一个)。你要哪个?

标签: python pandas date timestamp date-formatting


【解决方案1】:

标头设置不正确,因此要设置正确的标头,您可以使用

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 巴达霍斯 巴达霍斯 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

【讨论】:

  • 如果你得到了你想要的东西,请接受答案@Max 它会有所帮助。
猜你喜欢
  • 2021-12-06
  • 2018-05-26
  • 2018-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-08
相关资源
最近更新 更多