简体   繁体   English

在Pandas DataFrame中为行的子集增加时间

[英]Add time to a subset of rows in a pandas DataFrame

The code below produces a df: 下面的代码产生一个df:

import pandas as pd
import random
from datetime import timedelta

def randomTime():

    rtime = int(random.random()*86400)

    hours   = int(rtime/3600)
    minutes = int((rtime - hours*3600)/60)
    seconds = rtime - hours*3600 - minutes*60

    time_string = '%02d:%02d:%02d' % (hours, minutes, seconds)
    return time_string

time = [randomTime() for _ in range(8)]

k = 5
N = 8

d = ({'Time' : (time),
    'Events' : ['ABC','DEF','GHI','JKL','ABC','DEF','GHI','JKL'],
    'Number1' : ['xx','xx',1,'xx','xx','xx',2,'xx'],
    'Number2' : ['xx',1,'xx',1,'xx',2,'xx',2]})

df = pd.DataFrame(data=d)

I am trying to add time to selected rows of timestamps within a df. 我正在尝试将时间添加到df中选定的时间戳记行。 I'm trying to alter the last 4 timestamps to add 3 hours. 我正在尝试将最后4个时间戳更改为增加3小时。 At the moment it's producing strings. 目前,它正在产生琴弦。

df.iloc[4:8,3] = pd.TimedeltaIndex(df.iloc[4:8,3]) + timedelta(hours=3)

print(df)

Output:  
Events Number1 Number2            Time
0    ABC      xx      xx        14:25:51
1    DEF      xx       1        10:02:32
2    GHI       1      xx        01:23:32
3    JKL      xx       1        07:27:42
4    ABC      xx      xx  74325000000000
5    DEF      xx       2  38992000000000
6    GHI       2      xx  19158000000000
7    JKL      xx       2  26746000000000

I'm unsure if this is because the date is being added in the calculation here? 我不确定这是否是因为此处要在计算中添加日期? I'm not sure what I'm doing wrong. 我不确定自己在做什么错。

Your Time column is a column of strings. 您的Time列是一列字符串。 I'd recommend converting the entire column to timedelta first , and then adding those 3 hours. 我建议转换整个列timedelta 第一 ,然后加入那些3小时。 Otherwise, you end up mixing dtypes (string and timedelta), and weird things can happen. 否则,您最终会混用dtypes(字符串和timedelta),并且可能会发生奇怪的事情。

df['Time'] = pd.to_timedelta(df.Time, errors='coerce')
df.iloc[4:8, 3] += pd.Timedelta(hours=3)

df

  Events Number1 Number2            Time
0    ABC      xx      xx 0 days 13:51:35
1    DEF      xx       1 0 days 23:14:11
2    GHI       1      xx 0 days 02:16:28
3    JKL      xx       1 0 days 05:25:40
4    ABC      xx      xx 0 days 15:40:15
5    DEF      xx       2 0 days 04:05:26
6    GHI       2      xx 0 days 15:48:06
7    JKL      xx       2 1 days 00:12:30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM