Python |使用熊猫处理日期和时间

在处理数据时,遇到时间序列数据非常常见。熊猫是处理时间序列数据时非常有用的工具。

null

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

代码#1: 创建日期数据框

Python3

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


输出:

图片[1]-Python |使用熊猫处理日期和时间-yiteyi-C++库

代码#2: 创建日期范围并显示基本特征

Python3

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

约会时间 功能可分为两类。第一次是某个时期的某个时刻,第二次是某个时期以来的某个时刻。这些特征对于理解数据中的模式非常有用。

将给定日期划分为多个要素——

熊猫。系列dt。年 返回日期时间的年份。 熊猫。系列dt。月 返回日期时间的月份。 熊猫。系列dt。白天 返回日期时间的日期。 熊猫。系列dt。小时 返回日期时间的小时数。 熊猫。系列dt。分钟 返回日期时间的分钟数。 全部转介 约会时间 来自 在这里 .

代码#3: 将日期和时间分解为不同的功能

Python3

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


输出:

图片[2]-Python |使用熊猫处理日期和时间-yiteyi-C++库

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

Python3

# Input present datetime using Timestamp
t = pandas.tslib.Timestamp.now()
t


Timestamp('2018-09-18 17:18:49.101496')

Python3

# Convert timestamp to datetime
t.to_datetime()


datetime.datetime(2018, 9, 18, 17, 18, 49, 101496)

Python3

# Directly access and print the features
t.year
t.month
t.day
t.hour
t.minute
t.second


20188251553

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

Python3

import pandas as pd
# read csv file
df = pd.read_csv(url)
df.head()


输出:

图片[3]-Python |使用熊猫处理日期和时间-yiteyi-C++库

Python3

# Convert the Time column to datetime format
df[ 'Time' ] = pd.to_datetime(df.Time)
df.head()


图片[4]-Python |使用熊猫处理日期和时间-yiteyi-C++库

Python3

# shows the type of each column data
df.dtypes


City                       objectColors Reported            objectShape Reported             objectState                      objectTime               datetime64[ns]dtype: object

Python3

# Get hour detail from time data
df.Time.dt.hour.head()


0    221    202    143    134    19Name: Time, dtype: int64

Python3

# Get name of each date
df.Time.dt.weekday_name.head()


0     Sunday1     Monday2     Sunday3     Monday4    TuesdayName: Time, dtype: object

Python3

# Get ordinal day of the year
df.Time.dt.dayofyear.head()


0    1521    1812     463    1524    108Name: Time, dtype: int64
© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享