如何从一组日期列中获取最大日期值

时间:2018-08-28 14:43:44

标签: python python-3.x pandas numpy datetime

这是示例数据:

import pandas as pd
d = {'name': ['john', 'tom', 'phill', 'nero', 'bob', 'rob'], 'date1' :['2015-10-05', '2015-01-05', '2015-07-06', '2015-10-06', '2015-10-06', '2015-12-08'], 'date2' :['2015-10-05', '2015-01-05', '2015-07-06', '2015-08-06', '2015-09-06', '2015-12-08'], 'date3' :['2015-07-05', '2015-11-05', '2015-07-06', '2015-11-06', '2015-05-06', '2015-05-08']}
df2 = pd.DataFrame(data = d)
df2['date1'] = pd.DatetimeIndex(df2['date1'])
df2['date2'] = pd.DatetimeIndex(df2['date2'])
df2['date3'] = pd.DatetimeIndex(df2['date3'])

这是桌子

enter image description here

问题1:我想创建一个新列max_date,它将为每一行提供最大日期值。我以为我可以创建这些列的列表,然后将max应用于它们,但这没有用。我找到了numpy.amax(),但无法正常工作。

问题2:我必须使用列名来指定那些列,不能使用df2 [,0:2]之类的列的位置索引

  

更新-问题2-当我说“使用列名”时-我的意思是我有一个列名列表,我需要使用这些列名,例如[date1,date2,   date3]。抱歉,如果我的帖子不清楚。

3 个答案:

答案 0 :(得分:6)

select_dtypes

这对所有日期时间列均有效,无论命名约定如何。

df2.assign(max_date=df2.select_dtypes('datetime').max(1))

       date1      date2      date3   name   max_date
0 2015-10-05 2015-10-05 2015-07-05   john 2015-10-05
1 2015-01-05 2015-01-05 2015-11-05    tom 2015-11-05
2 2015-07-06 2015-07-06 2015-07-06  phill 2015-07-06
3 2015-10-06 2015-08-06 2015-11-06   nero 2015-11-06
4 2015-10-06 2015-09-06 2015-05-06    bob 2015-10-06
5 2015-12-08 2015-12-08 2015-05-08    rob 2015-12-08

答案 1 :(得分:5)

maxfilter like一起使用

df2['max_date']=df2.filter(like='date',axis=1).max(1)
df2
Out[157]: 
       date1      date2      date3   name   max_date
0 2015-10-05 2015-10-05 2015-07-05   john 2015-10-05
1 2015-01-05 2015-01-05 2015-11-05    tom 2015-11-05
2 2015-07-06 2015-07-06 2015-07-06  phill 2015-07-06
3 2015-10-06 2015-08-06 2015-11-06   nero 2015-11-06
4 2015-10-06 2015-09-06 2015-05-06    bob 2015-10-06
5 2015-12-08 2015-12-08 2015-05-08    rob 2015-12-08

答案 2 :(得分:3)

您可以通过App.incoming = function (req, cb) { console.log(req); // the files are available as req.files. // the body fields are available in req.body cb(null, 'Hey there, ' + req.body.sender); } App.remoteMethod( 'incoming', { accepts: [ { arg: 'req', type: 'object', http: function (ctx) { return ctx.req; } }], returns: { arg: 'summary', type: 'string' } } ); 使用布尔索引:

str.startswith