编写一个 Python 程序,为给定的数据框本地化亚洲时区
假设您有时间序列并且结果会作为本地化亚洲时区显示,如下所示,
Index is: DatetimeIndex(['2020-01-05 00:30:00+05:30', '2020-01-12 00:30:00+05:30', '2020-01-19 00:30:00+05:30', '2020-01-26 00:30:00+05:30', '2020-02-02 00:30:00+05:30'], dtype='datetime64[ns, Asia/Calcutta]', freq='W-SUN')
解决方案
定义数据框
使用pd.date_range()函数创建时间序列,其中开始时间为‘2020-01-01 00:30’,周期为5,时区为‘Asia/Calcutta’,然后将其存储为time_index。
time_index = pd.date_range('2020-01-01 00:30', periods = 5, freq ='W',tz = 'Asia/Calcutta')
设置df.index以存储time_index中本地化的时区
df.index = time_index
最后打印本地化的时区
示例
我们查看以下代码以更好地理解 -
import pandas as pd df = pd.DataFrame({'Id':[1,2,3,4,5], 'City':['Mumbai','Pune','Delhi','Chennai','Kolkata']}) time_index = pd.date_range('2020-01-01 00:30', periods = 5, freq ='W', tz = 'Asia/Calcutta') df.index = time_index print("DataFrame is:\n",df) print("Index is:\n",df.index)
输出
DataFrame is: Id City 2020-01-05 00:30:00+05:30 1 Mumbai 2020-01-12 00:30:00+05:30 2 Pune 2020-01-19 00:30:00+05:30 3 Delhi 2020-01-26 00:30:00+05:30 4 Chennai 2020-02-02 00:30:00+05:30 5 Kolkata Index is: DatetimeIndex(['2020-01-05 00:30:00+05:30', '2020-01-12 00:30:00+05:30', '2020-01-19 00:30:00+05:30', '2020-01-26 00:30:00+05:30', '2020-02-02 00:30:00+05:30'], dtype='datetime64[ns, Asia/Calcutta]', freq='W-SUN')
广告