Python使用Pandas处理日期和时间

2021年4月9日16:52:51 发表评论 774 次浏览

在处理数据时, 通常会遇到时间序列数据。Pandas在处理时间序列数据时是非常有用的工具。

Pandas提供了一套不同的工具, 通过这些工具, 我们可以对日期时间数据执行所有必要的任务。让我们尝试通过下面讨论的示例来理解。

代码1:创建日期数据框

import pandas as pd
  
# Create dates dataframe with frequency  
data = pd.date_range( '1/1/2011' , periods = 10 , freq = 'H' )
  
data

输出如下:

Python使用Pandas处理日期和时间1

代码2:创建日期范围并显示基本功能

# Create date and time with dataframe
data = pd.date_range( '1/1/2011' , periods = 10 , freq = 'H' )
  
x = datetime.now()
x.month, x.year

输出如下:

(9, 2018)

约会时间

Datetime特性可以分为两类。第一个时间点是在一个时间段内,第二个时间点是在一个特定时间段之后。这些特性对于理解数据中的模式非常有用。

将给定日期划分为功能-

panda.series.dt.year返回日期时间的年份。

pandas.Series.dt.month返回日期时间的月份。

pandas.Series.dt.day返回日期时间的日期。

pandas.Series.dt.hour返回日期时间的小时。

pandas.Series.dt.minute返回日期时间的分钟。

推荐全部数据时间来自的属性这里.

代码3:将数据和时间分解为单独的功能

# Create date and time with dataframe
rng = pd.DataFrame()
rng[ 'date' ] = pd.date_range( '1/1/2011' , periods = 72 , freq = 'H' )
  
# Print the dates in dd-mm-yy format
rng[: 5 ]
  
# Create features for year, month, day, hour, and minute
rng[ 'year' ] = rng[ 'date' ].dt.year
rng[ 'month' ] = rng[ 'date' ].dt.month
rng[ 'day' ] = rng[ 'date' ].dt.day
rng[ 'hour' ] = rng[ 'date' ].dt.hour
rng[ 'minute' ] = rng[ 'date' ].dt.minute
  
# Print the dates divided into features
rng.head( 3 )

输出如下:

Python使用Pandas处理日期和时间2

代码4:

要获取当前时间, 请使用Timestamp.now(), 然后将时间戳转换为日期时间, 并直接访问年, 月或日。

# Input present datetime using Timestamp
t = pandas.tslib.Timestamp.now()
t
Timestamp('2018-09-18 17:18:49.101496')
# Convert timestamp to datetime
t.to_datetime()
datetime.datetime(2018, 9, 18, 17, 18, 49, 101496)
# Directly access and print the features
t.year
t.month
t.day
t.hour
t.minute
t.second
2018
8
25
15
53

让我们在真实数据集uforeports上分析此问题。

import pandas as pd
  
url = 'http://bit.ly/uforeports'
  
# read csv file
df = pd.read_csv(url)           
df.head()

输出如下:

Python使用Pandas处理日期和时间3
# Convert the Time column to datatime format
df[ 'Time' ] = pd.to_datetime(df.Time)
  
df.head()
Python使用Pandas处理日期和时间4
# shows the type of each column data
df.dtypes
City                       object
Colors Reported            object
Shape Reported             object
State                      object
Time               datetime64[ns]
dtype: object
# Get hour detail from time data
df.Time.dt.hour.head()
0    22
1    20
2    14
3    13
4    19
Name: Time, dtype: int64
# Get name of each date
df.Time.dt.weekday_name.head()
0     Sunday
1     Monday
2     Sunday
3     Monday
4    Tuesday
Name: Time, dtype: object
# Get ordinal day of the year
df.Time.dt.dayofyear.head()
0    152
1    181
2     46
3    152
4    108
Name: Time, dtype: int64

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: