我有帶有UTC時(shí)間戳記的數(shù)據(jù)。我想將此時(shí)間戳的時(shí)區(qū)轉(zhuǎn)換為“ US / Pacific”,并將其作為層次結(jié)構(gòu)索引添加到pandas DataFrame。我已經(jīng)能夠?qū)r(shí)間戳轉(zhuǎn)換為索引,但是當(dāng)我嘗試將其作為列或索引添加回DataFrame時(shí),它將丟失時(shí)區(qū)格式。>>> import pandas as pd>>> dat = pd.DataFrame({'label':['a', 'a', 'a', 'b', 'b', 'b'], 'datetime':['2011-07-19 07:00:00', '2011-07-19 08:00:00', '2011-07-19 09:00:00', '2011-07-19 07:00:00', '2011-07-19 08:00:00', '2011-07-19 09:00:00'], 'value':range(6)})>>> dat.dtypes#datetime object#label object#value int64#dtype: object現(xiàn)在,如果我嘗試直接轉(zhuǎn)換系列,則會(huì)遇到錯(cuò)誤。>>> times = pd.to_datetime(dat['datetime'])>>> times.tz_localize('UTC')#Traceback (most recent call last):# File "<stdin>", line 1, in <module># File "/Users/erikshilts/workspace/schedule-detection/python/pysched/env/lib/python2.7/site-packages/pandas/core/series.py", line 3170, in tz_localize# raise Exception('Cannot tz-localize non-time series')#Exception: Cannot tz-localize non-time series如果將其轉(zhuǎn)換為索引,則可以將其作為時(shí)間序列進(jìn)行操作。注意,索引現(xiàn)在具有太平洋時(shí)區(qū)。>>> times_index = pd.Index(times)>>> times_index_pacific = times_index.tz_localize('UTC').tz_convert('US/Pacific')>>> times_index_pacific#<class 'pandas.tseries.index.DatetimeIndex'>#[2011-07-19 00:00:00, ..., 2011-07-19 02:00:00]#Length: 6, Freq: None, Timezone: US/Pacific但是,現(xiàn)在我遇到了將索引添加回?cái)?shù)據(jù)框的問(wèn)題,因?yàn)樗チ藭r(shí)區(qū)格式:>>> dat_index = dat.set_index([dat['label'], times_index_pacific])>>> dat_index# datetime label value#label #a 2011-07-19 07:00:00 2011-07-19 07:00:00 a 0# 2011-07-19 08:00:00 2011-07-19 08:00:00 a 1# 2011-07-19 09:00:00 2011-07-19 09:00:00 a 2#b 2011-07-19 07:00:00 2011-07-19 07:00:00 b 3# 2011-07-19 08:00:00 2011-07-19 08:00:00 b 4# 2011-07-19 09:00:00 2011-07-19 09:00:00 b 5您會(huì)注意到索引返回到UTC時(shí)區(qū),而不是轉(zhuǎn)換后的太平洋時(shí)區(qū)。如何更改時(shí)區(qū)并將其作為索引添加到DataFrame?
更改熊貓中日期-時(shí)間列的時(shí)區(qū)并添加為層次結(jié)構(gòu)索引
明月笑刀無(wú)情
2021-03-29 16:09:24