码迷,mamicode.com
首页 > 编程语言 > 详细

Python pandas Date

时间:2018-06-26 23:05:14      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:color   间隔   port   bubuko   ram   时间间隔   python   sunday   inf   

Pandas主要有4中与时间相关的类型。Timestamp, Period, DatetimeIndex,PeriodIndex.

import pandas as pd
import numpy as np
#
#Timestamp
pd.Timestamp(9/1/2016 10:05AM)
#output: Timestamp(‘2016-09-01 10:05:00‘)
#
#Period
pd.Period(1/2016)
#output: Period(‘2016-01‘, ‘M‘)
pd.Period(3/5/2016)
#output: Period(‘2016-03-05‘, ‘D‘)
#
#DatetimeIndex
t1 = pd.Series(list(abc), [pd.Timestamp(2016-09-01), pd.Timestamp(2016-09-02), pd.Timestamp(2016-09-03)])
t1
"""
2016-09-01    a
2016-09-02    b
2016-09-03    c
dtype: object
"""
type(t1.index)
#pandas.tseries.index.DatetimeIndex

#
#PeriodIndex
t2 = pd.Series(list(def), [pd.Period(2016-09), pd.Period(2016-10), pd.Period(2016-11)])
t2
"""
2016-09    d
2016-10    e
2016-11    f
Freq: M, dtype: object
"""
type(t2.index)
# pandas.tseries.period.PeriodIndex

1. 关于时间类型的转换

#Converting-to-Datetime
d1 = [2 June 2013, Aug 29, 2014, 2015-06-26, 7/12/16]
ts3 = pd.DataFrame(np.random.randint(10, 100, (4,2)), index=d1, columns=list(ab))
ts3

技术分享图片

ts3.index = pd.to_datetime(ts3.index)
ts3

技术分享图片

pd.to_datetime(4.7.12, dayfirst=True)
#output: Timestamp(‘2012-07-04 00:00:00‘)

2. 时间间隔

##Timedeltas
pd.Timestamp(9/3/2016)-pd.Timestamp(9/1/2016)
# Timedelta(‘2 days 00:00:00‘)
pd.Timestamp(9/2/2016 8:10AM) + pd.Timedelta(12D 3H)
# Timestamp(‘2016-09-14 11:10:00‘)

3. Dataframe中的时间

dates = pd.date_range(10-01-2016, periods=9, freq=2W-SUN)
dates
"""
DatetimeIndex([‘2016-10-02‘, ‘2016-10-16‘, ‘2016-10-30‘, ‘2016-11-13‘,
               ‘2016-11-27‘, ‘2016-12-11‘, ‘2016-12-25‘, ‘2017-01-08‘,
               ‘2017-01-22‘],
              dtype=‘datetime64[ns]‘, freq=‘2W-SUN‘)
"""
df = pd.DataFrame({Count 1: 100 + np.random.randint(-5, 10, 9).cumsum(),
                  Count 2: 120 + np.random.randint(-5, 10, 9)}, index=dates)
df

技术分享图片

df.index.weekday_name
"""
array([‘Sunday‘, ‘Sunday‘, ‘Sunday‘, ‘Sunday‘, ‘Sunday‘, ‘Sunday‘,
       ‘Sunday‘, ‘Sunday‘, ‘Sunday‘], dtype=object)
"""
df.diff()

技术分享图片

df.resample(M).mean()

技术分享图片

df[2017]

技术分享图片

df[2016-12]

技术分享图片

df[2016-12:]

技术分享图片

 

Python pandas Date

标签:color   间隔   port   bubuko   ram   时间间隔   python   sunday   inf   

原文地址:https://www.cnblogs.com/Shinered/p/9231619.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!