【问题标题】:What is the most efficient way to subtract rows of a dataframe (python pandas) by index in python pandas在python pandas中按索引减去数据帧(python pandas)行的最有效方法是什么
【发布时间】:2016-01-02 09:03:47
【问题描述】:

我有一个这样的数据框熊猫:

cEventID    arrivalTime
1167533 
1167541 2015-07-14 04:01:21
1167545 2015-07-14 04:03:20
1167549 2015-07-14 04:07:45
1167552 2015-07-14 04:10:21
1167553 2015-07-14 04:13:39
1167558 2015-07-14 04:15:58
1167561 2015-07-14 04:20:23

我需要减去一个事件和另一个事件之间的时间,结果是:

EventID arrivalTime diff time
1167541 2015-07-14 04:01:21 0
1167545 2015-07-14 04:03:20 00:01:59
1167549 2015-07-14 04:07:45 00:04:25
1167552 2015-07-14 04:10:21 00:02:36
1167553 2015-07-14 04:13:39 00:03:18
1167558 2015-07-14 04:15:58 00:02:19
1167561 2015-07-14 04:20:23 00:04:25

我通过一个关于 pandas 数据帧的 for 循环得到这个结果,for index, row in datos.iterrows():。我的功能是:

def llegadas(datos, estacion):     
    datos = datos       
    lista = []
    filas = []
    segundos = []
    for index, row in datos.iterrows():
        if index == 0: 
            lista.append('00:00:00')  
            filas.append(row)
        else:
            ii = filas[len(filas)-1][6] 
            ff = datos['arrivalTime'][index]
            deltat = str( dt.datetime.strptime(ff, '%Y-%m-%d %H:%M:%S') - dt.datetime.strptime(ii, '%Y-%m-%d %H:%M:%S') )
            lista.append(deltat)
            filas.append(row)

    df1 = pd.DataFrame(lista)
    frames = [datos, df1]
    datos = pd.concat(frames, axis=1)
    datos.rename(columns={0:'dif_tiempo'}, inplace=True)
    return datos

请提出一种使函数更有效的方法。

非常感谢您。

【问题讨论】:

    标签: python python-2.7 for-loop pandas dataframe


    【解决方案1】:

    difffillna 一起使用:

    In [4]:
    df['diff time'] = df['arrivalTime'].diff().fillna(0)
    df
    
    Out[4]:
       cEventID         arrivalTime  diff time
    0   1167533                 NaT   00:00:00
    1   1167541 2015-07-14 04:01:21   00:00:00
    2   1167545 2015-07-14 04:03:20   00:01:59
    3   1167549 2015-07-14 04:07:45   00:04:25
    4   1167552 2015-07-14 04:10:21   00:02:36
    5   1167553 2015-07-14 04:13:39   00:03:18
    6   1167558 2015-07-14 04:15:58   00:02:19
    7   1167561 2015-07-14 04:20:23   00:04:25
    

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多