gpt4 book ai didi

python - 如何从 Pandas DateTime Index 中删除时间值?

转载 作者:行者123 更新时间:2023-11-30 22:47:27 26 4
gpt4 key购买 nike

从 cvs 文件中读取。

df = pd.read_csv(filename, sep=";", names=['DateTime','Open','High','Low','Close','Vol'],
parse_dates = [0], index_col = 'DateTime')

输出数据:

                            Open     High      Low    Close
DateTime
2016-01-03 00:00:00+00:00 1.08701 1.08723 1.08451 1.08515
2016-01-04 00:00:00+00:00 1.08701 1.09464 1.07811 1.08239
2016-01-05 00:00:00+00:00 1.08238 1.08388 1.07106 1.07502
2016-01-06 00:00:00+00:00 1.07504 1.07994 1.07185 1.07766
2016-01-07 00:00:00+00:00 1.07767 1.09401 1.07710 1.09256
2016-01-08 00:00:00+00:00 1.09255 1.09300 1.08030 1.09218

如何从上述日期时间索引中删除时间值?

另一个问题,如何将开盘价/最高价/最低价/收盘价中的值截断为小数点后 6 位?

最佳答案

要截断日期时间,首先将对象放入 DateTime 对象中,因为它会对此进行适当的处​​理。例如,在打印时,它只会打印日期值,因为时间始终为 0。

>>> c = pd.read_csv("a.csv", sep=",", names=['DateTime','Open','High','Low','Close','Vol'])
>>> c
DateTime Open High Low Close Vol
0 2016-01-03 00:00:00+00:00 1.08701 1.08723 1.08451 1.08515 NaN
1 2016-01-04 00:00:00+00:00 1.08701 1.09464 1.07811 1.08239 NaN
2 2016-01-05 00:00:00+00:00 1.08238 1.08388 1.07106 1.07502 NaN
3 2016-01-06 00:00:00+00:00 1.07504 1.07994 1.07185 1.07766 NaN
4 2016-01-07 00:00:00+00:00 1.07767 1.09401 1.07710 1.09256 NaN
5 2016-01-08 00:00:00+00:00 1.09255 1.09300 1.08030 1.09218 NaN
>>> c.DateTime = pd.to_datetime(c.DateTime)
>>> c
DateTime Open High Low Close Vol
0 2016-01-03 1.08701 1.08723 1.08451 1.08515 NaN
1 2016-01-04 1.08701 1.09464 1.07811 1.08239 NaN
2 2016-01-05 1.08238 1.08388 1.07106 1.07502 NaN
3 2016-01-06 1.07504 1.07994 1.07185 1.07766 NaN
4 2016-01-07 1.07767 1.09401 1.07710 1.09256 NaN
5 2016-01-08 1.09255 1.09300 1.08030 1.09218 NaN

这通常会节省时间(如果存在的话),只是这里不显示它,因为时间值为 0。要仅获取日期,请执行以下操作:

>>> c.DateTime = c.DateTime.dt.date
>>> c.DateTime[0]
datetime.date(2016, 1, 3)

关于python - 如何从 Pandas DateTime Index 中删除时间值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40540179/

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