Search code examples
pythonpandasdataframejupyter-notebookcalculated-columns

Subtraction of two columns of the same dataframe


I want to do a subtraction of two columns of the same dataframe, col1 the row should be in a position [i+1] and the col2 in position [I]. (col 1 is the successor of col2).

The part of code that I can share, issue on the last return:

def calcul_TAT2(df):
    i=0
    for i in (range(len(df))):
        if  type(df['actual_gate_arrival_time']) is float or type(df['actual_gate_departure_time']) is float:
            return 'NaN'
        if  df['actual_gate_arrival_time'].lower() =='nan' or df['actual_gate_departure_time'].lower()=='nan':
            return 'NaN'
        else :
            actual_gate_arrival_time= (datetime(int(df['actual_gate_arrival_time'][6:10]),int(df['actual_gate_arrival_time'][3:5]),int(df['actual_gate_arrival_time'][:2]),int(df['actual_gate_arrival_time'][11:13]),int(df['actual_gate_arrival_time'][14:])))
            actual_gate_departure_time= (datetime(int(df['actual_gate_departure_time'][6:10]),int(df['actual_gate_departure_time'][3:5]),int(df['actual_gate_departure_time'][:2]),int(df['actual_gate_departure_time'][11:13]),int(df['actual_gate_departure_time'][14:])))       
        return df.loc[i+1,'actual_gate_departure_time']-df.loc[i,'actual_gate_arrival_time'] 
DHA['TAT']=DHA.apply(calcul_TAT2, axis=1)

TypeError: ("cannot do label indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [1] of <class 'int'>", 'occurred at index 593484569.0')

Solution

  • Try df['col3'] = df['col1'].shift(-1) - df['col2']