📜  在 Pandas 中使用 Timedelta 和 Period 创建基于 DateTime 的索引

📅  最后修改于: 2022-05-13 01:54:38.653000             🧑  作者: Mango

在 Pandas 中使用 Timedelta 和 Period 创建基于 DateTime 的索引

现实生活中的数据通常由基于日期和时间的记录组成。从天气数据到测量大型组织中的其他一些指标,他们通常依赖于将观察到的数据与一些时间戳相关联,以评估一段时间内的性能。

我们已经讨论了如何在 pandas 中操作日期和时间,现在让我们看看使用这些创建的时间戳、周期和索引的概念。

使用时间戳:
Timestamp 是 Python 的 Datetime 的 pandas 等价物,在大多数情况下可以与它互换。它表示一个特定的时间点。让我们看看如何创建时间戳。

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

输出 :

在我们用它创建索引之前,单独的时间戳并不是很有用。我们使用 Timestamps 创建的索引是DatetimeIndex类型。

# 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 Timestamps
index_ = [pd.Timestamp('01-06-2018'), pd.Timestamp('04-06-2018'),
          pd.Timestamp('07-06-2018'), pd.Timestamp('10-06-2018')]
  
# Let's set the index of the dataframe
df.index = index_
  
# Let's visualize the dataframe
print(df)

输出 :

现在我们将看到由单个时间戳组成的数据帧索引的类型。

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

输出 :

正如我们在输出中清楚地看到的那样,我们数据帧的索引类型是“DatetimeIndex”。使用 Periods :与代表时间点的 Timestamp 不同,Periods 代表一段时间。可以是月、日、年、小时等。让我们看看如何在 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 对象在用作 Dataframe 或 Series 中的索引之前并不是很有用。由 Periods 组成的索引称为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)

输出 :

现在我们将看到由各个周期组成的数据帧索引的类型。

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

输出 :

正如我们在输出中看到的,使用句点创建的索引称为 PeriodIndex。