gpt4 book ai didi

Python/Datetime/Pandas - 更改日期时间格式

转载 作者:太空宇宙 更新时间:2023-11-04 05:39:03 26 4
gpt4 key购买 nike

我有这个 Pandas 数据框:

             Value
Date
2015-06-01 6.9
2015-07-01 7.5
2015-08-01 7.6
2015-09-01 7.6
2015-10-01 7.9
2015-11-01 7.5

我正在使用这段代码访问它的最后一个索引项:

somedate=dict.index[-1]

它已经是日期时间格式。当我 print somedate 时,我得到以下信息:

2015-11-01 00:00:00
2015-11-01 00:00:00

(不知道为什么它分两行,但无论如何它工作正常)

我正在使用同一日期从 Pandas 构建另一个数据框:

            Prediction  MAPE  Score
2015-11-01 7.93 1.83 1

好吧,我只需要在最后一帧中将 2015-11-01 显示为 2015-11

我可以在变量 somedate 中解决这个问题吗?或者这是我在构建数据框时需要调整的内容?

OBS.: 我尝试使用 datetime.strptime,但它似乎只适用于字符串日期,而不适用于时间戳。

最佳答案

IIUC 你需要DatetimeIndex.to_period :

print df

# Prediction MAPE Score
#
#2015-11-01 7.93 1.83 1

print df.index

#DatetimeIndex(['2015-11-01'], dtype='datetime64[ns]', name=u'', freq=None)

df.index = df.index.to_period('M')
print df

# Prediction MAPE Score
#
#2015-11 7.93 1.83 1

或者您可以使用 DataFrame.to_period :

df = df.to_period('M')
print df

# Prediction MAPE Score
#
#2015-11 7.93 1.83 1

编辑:

我认为index的dtype不是datetime而是object,所以可以转换一下:

import pandas as pd
import io

temp=u"""Prediction;MAPE;Score
2015-11-01;7.93;1.83;1"""
df = pd.read_csv(io.StringIO(temp), sep=";", index_col=None)
df.index.name = ''
print df

# Prediction MAPE Score
#
#2015-11-01 7.93 1.83 1

print df.index
#Index([u'2015-11-01'], dtype='object', name=u'')

#convert index to datetime
df.index = pd.to_datetime(df.index)

df = df.to_period('M')
print df

# Prediction MAPE Score
#
#2015-11 7.93 1.83 1

关于Python/Datetime/Pandas - 更改日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34706273/

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