python pandas 时间差中的一列时间差怎么以秒为单位转为

Pandas处理大数据的一些小技巧 - 推酷
Pandas处理大数据的一些小技巧
近期的工作和Hive SQL打交道比较多,偶尔遇到一些SQL不好解决的问题,会将文件下载下来用pandas来处理,由于数据量比较大,因此有一些相关的经验可以和大家分享
近期的工作和Hive SQL打交道比较多,偶尔遇到一些SQL不好解决的问题,会将文件下载下来用pandas来处理,由于数据量比较大,因此有一些相关的经验可以和大家分享。
大文本数据的读写
有时候我们会拿到一些很大的文本文件,完整读入内存,读入的过程会很慢,甚至可能无法读入内存,或者可以读入内存,但是没法进行进一步的计算,这个时候如果我们不是要进行很复杂的运算,可以使用read_csv提供的chunksize或者iterator参数,来部分读入文件,处理完之后再通过to_csv的mode='a',将每部分结果逐步写入文件。
to_csv, to_excel的选择
在输出结果时统称会遇到输出格式的选择,平时大家用的最多的.csv, .xls, .xlsx,后两者一个是excel2003,一个是excel2007,我的经验是csv&xls&xlsx,大文件输出csv比输出excel要快的多,xls只支持60000+条记录,xlsx虽然支持记录变多了,但是,如果内容有中文常常会出现诡异的内容丢失。因此,如果数量较小可以选择xls,而数量较大则建议输出到csv,xlsx还是有数量限制,而且
量的话,会让你觉得python都死掉了
读入时处理日期列
我之前都是在数据读入后通过to_datetime函数再去处理日期列,如果数据量较大这又是一个浪费时间的过程,其实在读入数据时,可以通过parse_dates参数来直接指定解析为日期的列。它有几种参数,TRUE的时候会将index解析为日期格式,将列名作为list传入则将每一个列都解析为日期格式
关于to_datetime函数再多说几句,我们拿到的时期格式常常出现一些乱七八糟的怪数据,遇到这些数据to_datimetime函数默认会报错,其实,这些数据是可以忽略的,只需要在函数中将errors参数设置为'ignore'就可以了。
另外,to_datetime就像函数名字显示的,返回的是一个时间戳,有时我们只需要日期部分,我们可以在日期列上做这个修改,datetime_col = datetime_col.apply(lambda x: x.date()),用map函数也是一样的datetime_col = datetime_col.map(lambda x: x.date())
把一些数值编码转化为文字
前面提到了map方法,我就又想到了一个小技巧,我们拿到的一些数据往往是通过数字编码的,比如我们有gender这一列,其中0代表男,1代表女。当然我们可以用索引的方式来完成
其实我们有更简单的方法,对要修改的列传入一个dict,就会达到同样的效果。
通过shift函数求用户的相邻两次登录记录的时间差
之前有个项目需要计算用户相邻两次登录记录的时间差,咋看起来其实这个需求很简单,但是数据量大起来的话,就不是一个简单的任务,拆解开来做的话,需要两个步骤,第一步将登录数据按照用户分组,再计算每个用户两次登录之间的时间间隔。数据的格式很单纯,如下所示
如果数据量不大的,可以先unique uid,再每次计算一个用户的两次登录间隔,类似这样
这种方法虽然计算逻辑比较清晰易懂,但是缺点也非常明显,计算量巨大,相当与有多少量记录就要计算多少次。
那么为什么说pandas的shift函数适合这个计算呢?来看一下shift函数的作用
刚好把值向下错位了一位,是不是恰好是我们需要的。让我们用shift函数来改造一下上面的代码。
上面的代码就把pandas向量化计算的优势发挥出来了,规避掉了计算过程中最耗费时间的按uid循环。如果我们的uid都是一个只要排序后用shift(1)就可以取到所有前一次登录的时间,不过真实的登录数据中有很多的不用的uid,因此再将uid也shift一下命名为uid0,保留uid和uid0匹配的记录就可以了。
【责任编辑:seeker TEL:(010)】
已发表评论数()
请填写推刊名
描述不能大于100个字符!
权限设置: 公开
仅自己可见
正文不准确
标题不准确
排版有问题
主题不准确
没有分页内容
图片无法显示
视频无法显示
与原文不一致11817人阅读
Pandas小记(9)
http://pandas 最基本的时间序列类型就是以时间戳(TimeStamp)为 index 元素的 Series 类型。其它时间序列处理相关的包[][]pandas时序数据文件读取dateparse = lambda dates: pd.datetime.strptime(dates, '%Y-%m')data = pd.read_csv('AirPassengers.csv', parse_dates='Month', index_col='Month',date_parser=dateparse)print data.head()read_csv时序参数parse_dates:这是指定含有时间数据信息的列。正如上面所说的,列的名称为“月份”。index_col:使用pandas 的时间序列数据背后的关键思想是:目录成为描述时间数据信息的变量。所以该参数告诉pandas使用“月份”的列作为索引。date_parser:指定将输入的字符串转换为可变的时间数据。Pandas默认的数据读取格式是‘YYYY-MM-DD HH:MM:SS’?如需要读取的数据没有默认的格式,就要人工定义。这和dataparse的功能部分相似,这里的定义可以为这一目的服务。The default uses dateutil.parser.parser to do the conversion.[][]时间序列分析和处理Time Seriespandas has simple, powerful, and efficient functionality for performingresampling operations during frequency conversion (e.g., converting secondlydata into 5-minutely data). This is extremely common in, but not limited to,financial applications. 时序数据生成和表示c = pandas.Timestamp(' 00:00:08')In [103]: rng = pd.date_range('1/1/2012', periods=100, freq='S')
In [104]: ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng)
In [105]: ts.resample('5Min', how='sum')
Freq: 5T, dtype: int32
Time zone representationIn [106]: rng = pd.date_range('3/6/', periods=5, freq='D')
In [107]: ts = pd.Series(np.random.randn(len(rng)), rng)
In [108]: ts
Freq: D, dtype: float64
In [109]: ts_utc = ts.tz_localize('UTC')
In [110]: ts_utc
00:00:00+00:00
00:00:00+00:00
00:00:00+00:00
00:00:00+00:00
00:00:00+00:00
Freq: D, dtype: float64
时序转换Convert to another time zoneIn [111]: ts_utc.tz_convert('US/Eastern')
19:00:00-05:00
19:00:00-05:00
19:00:00-05:00
19:00:00-05:00
19:00:00-05:00
Freq: D, dtype: float64
Converting between time span representationsIn [112]: rng = pd.date_range('1/1/2012', periods=5, freq='M')
In [113]: ts = pd.Series(np.random.randn(len(rng)), index=rng)
In [114]: ts
Freq: M, dtype: float64
In [115]: ps = ts.to_period()
In [116]: ps
Freq: M, dtype: float64
In [117]: ps.to_timestamp()
Freq: MS, dtype: float64
Converting between period and timestamp enables some convenient arithmeticfunctions to be used. In the following example, we convert a quarterlyfrequency with year ending in November to 9am of the end of the month followingthe quarter end:In [118]: prng = pd.period_range('1990Q1', '2000Q4', freq='Q-NOV')
In [119]: ts = pd.Series(np.random.randn(len(prng)), prng)
In [120]: ts.index = (prng.asfreq('M', 'e') + 1).asfreq('H', 's') + 9
In [121]: ts.head()
Freq: H, dtype: float64
[][]时序处理相关函数&pandas.(*args, **kwargs)&&& Convert argument to datetime.lz觉得此函数一般是对不明确类型进行转换,如果直接对datetime类型转换太慢不值得,有其它方法。Series.dt.normalize(*args, **kwargs)&&& Return DatetimeIndex with times to midnight. Length is unaltered.直接调用应该就是只取datetime的date部分,即重置time部分,而保持datetime类型不变。DatetimeIndex.normalize()&&&&&&& Return DatetimeIndex with times to midnight. Length is unalteredDatetimeIndex相关的函数Note: pandas时间序列series的index必须是DatetimeIndex不能是Index,也就是如果index是从dataframe列中转换来的,其类型必须是datetime类型,不能是date、object等等其它类型!否则在很多处理包中会报错。ts.index返回DatetimeIndex(['', '', '', '', ... '', '', '', ''],&&&&&&&&&&&&& dtype='datetime64[ns]', name='time', length=481, freq=None)说明index类型是DatetimeIndex没错,但是freq=None说明datetime的频率没有自动推断出来,这里看起来应该freq=1也就是一天。freq也可以通过ts.index.inferred_freq查看series对象的dt存取器 .dt accessorSeries.()&&& Accessor object for datetimelike properties of the Series values.示例&&& s.dt.date&&& &&& s.dt.hour&&& &&& s.dt.second&&& &&& s.dt.quarterReturns a Series indexed like the original Series. Raises TypeError if the Series does not contain datetimelike values.Series datetime类型处理示例:将series中datetime类型只保留date部分而不改变数据类型,即数据类型仍为datetimes.map(pd.Timestamp.date) 或者 s.map(lambda x: pd.to_datetime(x.date()))但是pd.Timestamp.date会将数据的类型从datetime类型转换成date类型,在pd中显示是object类型;而转换成datetime的函数pd.to_datetime特别慢而耗时。一个最好的转换方式是直接进行类型转换Converting to datetime64[D]:df.dates.values.astype('M8[D]') Though re-assigning that to a DataFrame col will revert it back to [ns].所以可以这样实现user_pay_df['time'] = user_pay_df['time'].dt.date.astype('M8[D]')或者user_pay_df['time'] = user_pay_df['time'].dt.date.astype(np.datetime64)不过这仍不是最快的方法,lz找到一个更快的方法重置datetime的time部分user_pay_df['time'] = user_pay_df['time'].dt.normalize()[][]&&&&&&& uid&& sid&&&&&&&&&&&&&&& time0& 62
17:00:001&& 62
11:00:002& 62
15:00:00uid&&&&&&&&&&&&& int64sid&&&&&&&&&&&&& int64time&&& datetime64[ns]dtype: object&&&&&&& uid&& sid&&&&&& time0& 62 1&& 62 2& 62 uid&&&&&&&&&&&&& int64sid&&&&&&&&&&&&& int64time&&& datetime64[ns]pandas时序类型pandas 最基本的时间日期对象是一个从 Series 派生出来的子类 TimeStamp,这个对象与 datetime 对象保有高度兼容性,可通过&pd.to_datetime()&函数转换。(一般是从 datetime 转换为 Timestamp)lang:python
&&& pd.to_datetime(now)
Timestamp(' 15:56:19.313193', tz=None)
&&& pd.to_datetime(np.nan)
pandas 的时间序列pandas 最基本的时间序列类型就是以时间戳(TimeStamp)为 index 元素的 Series 类型。lang:python
&&& dates = [datetime(),datetime(),datetime()]
&&& ts = Series(np.random.randn(3),index=dates)
dtype: float64
&&& type(ts)
&class 'pandas.core.series.Series'&
&&& ts.index
&class 'pandas.tseries.index.DatetimeIndex'&
Length: 3, Freq: None, Timezone: None
&&& ts.index[0]
Timestamp(' 00:00:00', tz=None)
时间序列之间的算术运算会自动按时间对齐。 时间序列的索引、选取、子集构造时间序列只是 index 比较特殊的 Series ,因此一般的索引操作对时间序列依然有效。其特别之处在于对时间序列索引的操作优化。先在序列对象选择一个特殊值。可以通过以下两种方式实现:1 使用各种字符串进行索引:lang:python
&&& ts['']
&&& ts['']
&&& ts['01/01/2011']
2 Import the datetime library and use 'datetime' function:from datetime import datetime
ts[datetime()]3 你需要1949年所有的值,可以这样做:ts['1949']。可见,月份部分已经省略。如果你要获得某月所有的日期,日期部分也可以省略。对于较长的序列,还可以只传入 “年” 或 “年月” 选取切片:&&& ts
dtype: float64
&&& ts['2012']
dtype: float64
&&& ts['':'2012-12']
dtype: float64
4 除了这种字符串切片方式外,还有一种实例方法可用:ts.truncate(after='')。值得注意的是,切片时使用的字符串时间戳并不必存在于 index 之中,如&ts.truncate(before='3055')&也是合法的。 Time/Date ComponentsThere are several time/date properties that one can access from Timestamp or a collection of timestamps like a DateTimeIndex.yearThe year of the datetimemonthThe month of the datetimedayThe days of the datetimehourThe hour of the datetimeminuteThe minutes of the datetimesecondThe seconds of the datetimemicrosecondThe microseconds of the datetimenanosecondThe nanoseconds of the datetimedateReturns datetime.datetimeReturns datetime.timedayofyearThe ordinal day of yearweekofyearThe week ordinal of the yearweekThe week ordinal of the yeardayofweekThe numer of the day of the week with Monday=0, Sunday=6weekdayThe number of the day of the week with Monday=0, Sunday=6weekday_nameThe name of the day in a week (ex: Friday)quarterQuarter of the date: Jan=Mar = 1, Apr-Jun = 2, etc.days_in_monthThe number of days in the month of the datetimeis_month_startLogical indicating if first day of month (defined by frequency)is_month_endLogical indicating if last day of month (defined by frequency)is_quarter_startLogical indicating if first day of quarter (defined by frequency)is_quarter_endLogical indicating if last day of quarter (defined by frequency)is_year_startLogical indicating if first day of year (defined by frequency)is_year_endLogical indicating if last day of year (defined by frequency)Furthermore, if you have a Series with datetimelike values, then you can access these properties via the .dt accessor, see the .[Time/Date Components]日期的范围、频率以及移动pandas 中的时间序列一般被默认为不规则的,即没有固定的频率。但出于分析的需要,我们可以通过插值的方式将序列转换为具有固定频率的格式。一种快捷方式是使用&.resample(rule)&方法:lang:python
dtype: float64
&&& ts.resample('D')
Freq: D, dtype: float64
生成日期范围pd.date_range()&可用于生成指定长度的 DatetimeIndex。参数可以是起始结束日期,或单给一个日期,加一个时间段参数。日期是包含的。lang:python
&&& pd.date_range('','')
&class 'pandas.tseries.index.DatetimeIndex'&
Length: 10, Freq: D, Timezone: None
&&& pd.date_range(start='',periods=10)
&class 'pandas.tseries.index.DatetimeIndex'&
Length: 10, Freq: D, Timezone: None
&&& pd.date_range(end='',periods=10)
&class 'pandas.tseries.index.DatetimeIndex'&
Length: 10, Freq: D, Timezone: None
默认情况下,date_range 会按天计算时间点。这可以通过 freq 参数进行更改,如 “BM” 代表 bussiness end of month。lang:python
&&& pd.date_range('','',freq='BM')
&class 'pandas.tseries.index.DatetimeIndex'&
Length: 5, Freq: BM, Timezone: None
频率和日期偏移量pandas 中的频率是由一个基础频率和一个乘数组成的。基础频率通常以一个字符串别名表示,如上例中的 “BM”。对于每个基础频率,都有一个被称为日期偏移量(date offset)的对象与之对应。可以通过实例化日期偏移量来创建某种频率:lang:python
&&& Hour()
&&& Hour(2)
&2 * Hours&
&&& Hour(1) + Minute(30)
&90 * Minutes&
但一般来说不必这么麻烦,使用前面提过的字符串别名来创建频率就可以了:lang:python
&&& pd.date_range('00:00','12:00',freq='1h20min')
&class 'pandas.tseries.index.DatetimeIndex'&
[ 00:00:00, ...,
Length: 10, Freq: 80T, Timezone: None
可用的别名,可以通过 help() 或 文档来查询,这里就不写了。移动(超前和滞后)数据移动(shifting)指的是沿着时间轴将数据前移或后移。Series 和 DataFrame 都有一个&.shift()&方法用于执行单纯的移动操作,index 维持不变:lang:python
dtype: float64
&&& ts.shift(2)
dtype: float64
&&& ts.shift(-2)
dtype: float64
上例中因为移动操作产生了 NA 值,另一种移动方法是移动 index,而保持数据不变。这种移动方法需要额外提供一个 freq 参数来指定移动的频率:lang:python
&&& ts.shift(2,freq='D')
dtype: float64
&&& ts.shift(2,freq='3D')
dtype: float64
时期及其算术运算本节使用的时期(period)概念不同于前面的时间戳(timestamp),指的是一个时间段。但在使用上并没有太多不同,pd.Period&类的构造函数仍需要一个时间戳,以及一个 freq 参数。freq 用于指明该 period 的长度,时间戳则说明该 period 在公园时间轴上的位置。lang:python
&&& p = pd.Period(2010,freq='M')
Period('2010-01', 'M')
Period('2010-03', 'M')
上例中我给 period 的构造器传了一个 “年” 单位的时间戳和一个 “Month” 的 freq,pandas 便自动把 2010 解释为了 2010-01。period_range 函数可用于创建规则的时间范围:lang:python
&&& pd.period_range('2010-01','2010-05',freq='M')
&class 'pandas.tseries.period.PeriodIndex'&
[2010-01, ..., 2010-05]
PeriodIndex 类保存了一组 period,它可以在任何 pandas 数据结构中被用作轴索引:lang:python
&&& Series(np.random.randn(5),index=pd.period_range('201001','201005',freq='M'))
Freq: M, dtype: float64
时期的频率转换Period 和 PeriodIndex 对象都可以通过其&.asfreq(freq, method=None, how=None)&方法被转换成别的频率。lang:python
&&& p = pd.Period('2007',freq='A-DEC')
&&& p.asfreq('M',how='start')
Period('2007-01', 'M')
&&& p.asfreq('M',how='end')
Period('2007-12', 'M')
&&& ts = Series(np.random.randn(1),index=[p])
Freq: A-DEC, dtype: float64
&&& ts.asfreq('M',how='start')
Freq: M, dtype: float64
时间戳与时期间相互转换以时间戳和以时期为 index 的 Series 和 DataFrame 都有一对&.to_period()&和&to_timestamp(how='start')&方法用于互相转换 index 的类型。因为从 period 到 timestamp 的转换涉及到一个取端值的问题,所以需要一个额外的 how 参数,默认为 'start':lang:python
&&& ts = Series(np.random.randn(5),index=pd.period_range('201001','201005',freq='M'))
Freq: M, dtype: float64
&&& ts.to_timestamp()
Freq: MS, dtype: float64
&&& ts.to_timestamp(how='end')
Freq: M, dtype: float64
&&& ts.to_timestamp().to_period()
00:00:00.000
00:00:00.000
00:00:00.000
00:00:00.000
00:00:00.000
Freq: L, dtype: float64
&&& ts.to_timestamp().to_period('M')
Freq: M, dtype: float64
重采样及频率转换重采样(resampling)指的是将时间序列从一个频率转换到另一个频率的过程。pandas 对象都含有一个.resample(freq, how=None, axis=0, fill_method=None, closed=None, label=None, convention='start', kind=None, loffset=None, limit=None, base=0)&方法用于实现这个过程。本篇最前面曾用 resample 规整化过时间序列。当时进行的是插值操作,因为原索引的频率与给出的 freq 参数相同。resample 方法更多的应用场合是 freq 发生改变的时候,这时操作就分为升采样(upsampling)和降采样(downsampling)两种。具体的区别都体现在参数里。lang:python
Freq: M, dtype: float64
&&& ts.resample('D',fill_method='ffill')#升采样
Freq: D, Length: 151
&&& ts.resample('A-JAN',how='sum')#降采样
Freq: A-JAN, dtype: float64[]from: ref: [][][]
&&相关文章推荐
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:1619898次
积分:19502
积分:19502
排名:第374名
原创:521篇
转载:73篇
评论:169条
文章:21篇
阅读:85035
阅读:22998
文章:13篇
阅读:46630
阅读:27693
文章:16篇
阅读:78585
文章:18篇
阅读:42530
Contact meRelated posts
微信公众号pandas中将timestamp转为datetime
pandas中将timestamp转为datetime
发布时间: 12:03:59
编辑:www.fx114.net
本篇文章主要介绍了"pandas中将timestamp转为datetime ",主要涉及到pandas中将timestamp转为datetime 方面的内容,对于pandas中将timestamp转为datetime 感兴趣的同学可以参考一下。
参考自:在pandas DataFrame中将timestamp转为datetime,关键要使用unit='s'。而不是ms、us或者其他选项。0
.123213,转换为datetimeIn [106]:pd.to_datetime(df['timestamp'], unit='s')Out[106]:index0
07:00:00Name: timestamp, dtype: datetime64[ns]转为字符串In [107]:pd.to_datetime(df['timestamp'], unit='s').dt.strftime('%Y-%m-%d %H:%M')Out[107]:index0
07:00Name: timestamp, dtype: object
一、不得利用本站危害国家安全、泄露国家秘密,不得侵犯国家社会集体的和公民的合法权益,不得利用本站制作、复制和传播不法有害信息!
二、互相尊重,对自己的言论和行为负责。
本文标题:
本页链接:

我要回帖

更多关于 pandas 转为字典 的文章

 

随机推荐