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

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

现实生活中的数据往往由基于日期和时间的记录组成。从天气数据到大组织中的一些其他指标的测量,他们经常依赖于将观察到的数据与一些时间戳联系起来,以评估一段时间的表现。

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

使用时间戳:
Timestamp相当于Python的Datetime,在大多数情况下可以和它互换。它表示一个特定的时间点。让我们来看看如何创建Timestamp。

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

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

单独的时间戳并不是很有用,直到我们用它来创建一个索引。我们使用时间戳创建的索引是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)

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

现在我们将看到数据框架索引的类型,它是由单个时间戳组成的。

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

输出 :
在Pandas中使用Timedelta和Period来创建基于DateTime的索引
正如我们在输出中可以清楚地看到,我们的数据框架的索引类型是 “DatetimeIndex”。

使用Periods :与代表一个时间点的Timestamp不同,Periods代表一个时间段。它可以是一个月、一天、一年、一小时等等。让我们看看如何在Pandas中创建Periods。

# 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)

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

输出中的’M’代表月份。

单独的Period对象并不十分有用,直到它被用作数据框架或系列中的索引。一个由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)

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

现在我们将看到我们的数据框架索引的类型,它是由各个周期组成的。

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

输出 :
在Pandas中使用Timedelta和Period来创建基于DateTime的索引
正如我们在输出中看到的,使用周期创建的索引被称为PeriodIndex。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程