Python | Панды Series.tz_convert

Опубликовано: 28 Марта, 2022

Python - отличный язык для анализа данных, в первую очередь из-за фантастической экосистемы пакетов Python, ориентированных на данные. Pandas - один из таких пакетов, который значительно упрощает импорт и анализ данных.

Серия Pandas - это одномерный массив ndarray с метками осей. Этикетки не обязательно должны быть уникальными, но должны быть хешируемого типа. Объект поддерживает индексирование как на основе целых чисел, так и на основе меток и предоставляет множество методов для выполнения операций, связанных с индексом.

Pandas Series.tz_convert() function works with time zone aware indexes. It convert tz-aware axis to target time zone.

Syntax: Series.tz_convert(tz, axis=0, level=None, copy=True)

Parameter :
tz : string or pytz.timezone object
axis : the axis to convert
level : int, str, default None
copy : Also make a copy of the underlying data.

Returns : Series

Example #1: Use Series.tz_convert() function to convert the time zone aware index of the given Series to the target time zone.

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(["New York", "Chicago", "Toronto", "Lisbon", "Rio", "Moscow"])
  
# Create the Datetime Index
didx = pd.DatetimeIndex(start ="2014-08-01 10:00", freq ="W"
                           periods = 6, tz = "Asia/Calcutta"
  
# set the index
sr.index = didx
  
# Print the series
print(sr)

Выход :

Now we will use Series.tz_convert() function to convert the given time zone index to time zone aware index to the target time zone which is ‘US/Central’.

# convert to "US / Central"
sr.tz_convert("US/Central")

Output :

As we can see in the output, the Series.tz_convert() function has converted the time zone of the index of the given series object to the desired time zone.
 
Example #2: Use Series.tz_convert() function to convert the time zone aware index of the given Series to the target time zone.

# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002])
  
# Create the Datetime Index
didx = pd.DatetimeIndex(start ="2014-08-01 10:00", freq ="W"
                     periods = 5, tz = "Asia/Calcutta"
  
# set the index
sr.index = didx
  
# Print the series
print(sr)

Выход :

Now we will use Series.tz_convert() function to convert the given time zone index to time zone aware index to the target time zone which is ‘Europe/Berlin’

# convert to "Europe / Berlin"
sr.tz_convert("Europe/Berlin")

Выход :

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.