Использование Timedelta и Period для создания индексов на основе DateTime в Pandas

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

Данные реальной жизни часто состоят из записей, основанных на дате и времени. От данных о погоде до измерения некоторых других показателей в крупных организациях они часто полагаются на связывание наблюдаемых данных с некоторой временной меткой для оценки производительности с течением времени.

Мы уже обсуждали, как управлять датой и временем в пандах, теперь давайте посмотрим на концепции временных меток, периодов и индексов, созданных с их помощью.

Using Timestamps :
Timestamp is the pandas equivalent of Python’s Datetime and is interchangeable with it in most cases. It denotes a specific point in time. Let’s see how to create Timestamp.

# importing pandas as pd
import pandas as pd
  
# Creating the timestamp
ts = pd.Timestamp("02-06-2018")
  
# Print the timestamp
print(ts)

Выход :

Timestamps alone is not very useful, until we create an index out of it. The index that we create using the Timestamps are of DatetimeIndex type.

Выход :

Now we will see the type of dataframe index which is made up of individual timestamps.

# Check the type
print(type(df.index))

Output :

As we can clearly see in the output, the type of the index of our dataframe is ‘DatetimeIndex’.
 
Using Periods : Unlike Timestamp which represents a point in time, Periods represents a period of time. It could be a month, day, year, hour etc.. Let’s see how to create Periods in Pandas.

# importing pandas as pd
import pandas as pd
  
# Let"s create the Period
# We have created a period
# of a month
pr = pd.Period("06-2018")
  
# Let"s print the period
print(pr)

Выход :

Буква «M» на выходе представляет месяц.

Period objects alone is not very useful until it is used as an Index in a Dataframe or a Series. An index made up of Periods are called PeriodIndex.

# importing pandas as pd
import pandas as pd
  
# Let"s create a dataframe
df = pd.DataFrame({"City":["Lisbon", "Parague", "Macao", "Venice"],
                    "Event":["Music", "Poetry", "Theatre", "Comedy"],
                    "Cost":[10000, 5000, 15000, 2000]})
  
  
# Let"s create an index using Periods
index_ = [pd.Period("02-2018"), pd.Period("04-2018"),
          pd.Period("06-2018"), pd.Period("10-2018")]
  
# Let"s set the index of the dataframe
df.index = index_
  
# Let"s visualize the dataframe
print(df)

Выход :

Now we will see the type of our dataframe index which is made up of individual Periods.

# Check the type
print(type(df.index))

Выход :

Как видно из выходных данных, индекс, созданный с использованием периодов, называется PeriodIndex.

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

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