用 Python 编写一个程序来为给定的数据框本地化亚洲时区
pythonpandasserver side programmingprogramming
假设您有一个时间序列,并且本地化亚洲时区的结果是,
索引为: 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’,periods=5 且 tz = ‘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')