按时计算后在数据框中添加新列

时间:2016-06-16 05:15:11

标签: python python-2.7 pandas

我有DataFrame这样:

          Name           first_seen       last_seen
   0      Random guy 1   5/22/2016 18:12  5/22/2016 18:15 
   1      Random guy 2   5/22/2016 12:03  5/22/2016 12:03 
   2      Random guy 3   5/22/2016 21:06  5/22/2016 21:06
   3      Random guy 4   5/22/2016 16:20  5/22/2016 16:20 
   4      Random guy 5   5/22/2016 14:46  5/22/2016 14:46 

现在我必须添加名为column的{​​{1}},当该人(Visit_period)花费的最长时间落入时,[morning,afternoon,evening,night]会占用row个值中的一个:

 - morning: 08:00 to 12:00 hrs
 - afternoon: 12:00 to 16:00 hrs
 - evening: 16:00 to 20:00 hrs
 - night: 20:00 to 24:00 hrs

所以对于上面的五行输出将是这样的。

   visit_period
        evening
      afternoon
          night
        evening
      afternoon  

我已经提到了花费的最长时间,因为有些人的first_seen可能在14:30而last_seen是16:21。我想分配值afternoon,因为他在下午的板上花了30分钟,在晚上的板上花了21分钟。 我使用的是python 2.7。

2 个答案:

答案 0 :(得分:1)

您可以使用apply以下main_visit_period功能尝试根据您列出的条件指定访问期限:

times = list(range(8, 21, 4))
labels = ['morning', 'afternoon', 'evening', 'night']
periods = dict(zip(times, labels))

给出:

{8: 'morning', 16: 'evening', 12: 'afternoon', 20: 'night'}

现在分配句点的功能:

def period(row):
    visit_start = {'hour': row.first_seen.hour, 'min': row.first_seen.minute} # get hour, min of visit start
    visit_end = {'hour': row.last_seen.hour, 'min': row.last_seen.minute} # get hour, min of visit end
    for period_start, label in periods.items():
        period_end = period_start + 4
        if period_start <= visit_start['hour'] < period_end:
            if period_start <= visit_end['hour'] < period_end or (period_end - visit_start['hour']) * 60 - visit_start['min'] > (visit_end['hour'] - period_end) * 60 + visit_end['min']:
                return label
            else:
                return periods[period_end] # assign label of following period  

最后.apply()

df['period'] = df.apply(period, axis=1)

得到:

           Name          first_seen           last_seen     period
0  Random guy 1 2016-05-22 18:12:00 2016-05-22 18:15:00    evening
1  Random guy 2 2016-05-22 12:03:00 2016-05-22 12:03:00  afternoon
2  Random guy 3 2016-05-22 21:06:00 2016-05-22 21:06:00      night
3  Random guy 4 2016-05-22 16:20:00 2016-05-22 16:20:00    evening
4  Random guy 5 2016-05-22 14:46:00 2016-05-22 14:46:00  afternoon

答案 1 :(得分:0)

你可以这样做:

start  = pd.datetime(2016, 05, 22, 8, 00, 00)
d = ["Morning", "Afternoon", "Evening", "Night"]

def max_spent(fs, ls):

    # Transform your date into timedelta in seconds:
    sr = np.arange(8,25,4)*3600
    fss = (fs-start).seconds
    lss = (ls-start).seconds

    # In which slot would it fit ?
    fs_d = sr.searchsorted(fss)
    ls_d = sr.searchsorted(lss)
    # If it's not the same for both date:
    if fs_d != ls_d:
        # get the one with the biggest amount of time:
        if fss - sr[fs_d - 1] > lss - sr[ls_d - 1]:
            return d[fs_d-1]
        else:
            return d[ls_d-1]
    else:
        return d[ls_d-1]

然后,你只需:

df["visit_period"] = df.apply(lambda x: max_spent(x["first_seen"], x["last_seen"]), axis=1)

你得到:

df 
   Name          first_seen           last_seen visit_period
0  guy1 2016-05-22 18:12:00 2016-05-22 18:15:00      Evening
1  guy2 2016-05-22 12:03:00 2016-05-22 12:03:00    Afternoon
2  guy3 2016-05-22 21:06:00 2016-05-22 21:06:00        Night
3  guy4 2016-05-22 16:20:00 2016-05-22 16:20:00      Evening
4  guy5 2016-05-22 14:46:00 2016-05-22 14:46:00    Afternoon
5  guy6 2016-05-22 14:30:00 2016-05-22 16:21:00    Afternoon

使用pd.cut的早期版本,我认为如果不需要评估哪些列是最佳的,我认为更好:

# Transform your date into timedelta in seconds:
df["sec"] = map(lambda x: x.seconds, df.last_seen-start)

# Apply Cut on this column:
df["visit_period"] = pd.cut(df.sec, np.arange(8,25,4)*3600, labels=d)

我只在last_seen上完成了它,但您可以使用相应值创建另一个列来执行最长花费的时间,然后您可以在该列上执行此操作。

HTH