pythonpandas

replace first row value with last row value


I'm trying to take the value from the last row of a df col and replace it with the first value. I'm returning a value error.

import pandas as pd
df = pd.DataFrame({'name': ['tom','jon','sam','jane','bob'],
       'age': [24,25,18,26,17],
       'Notification': [np.nan,'2025-01-03 14:19:35','2025-01-03 14:19:39','2025-01-03 14:19:41','2025-01-03 14:19:54'],
       'sex':['male','male','male','female','male']})

df_test = df.copy()

df_test['Notification'] = pd.to_datetime(df_test['Notification'])

df_test['Notification'].iloc[0] = df_test['Notification'].tail(1)

Error:

ValueError: Could not convert object to NumPy datetime

Solution

  • You need to edit this line:

    df.loc[df.index[0], 'age'] = df.loc[df.index[-1], 'age']
    

    Complete code:

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'name': ['tom', 'jon', 'sam', 'jane', 'bob'],
                   'age': [np.nan, 25, 18, 26, 17],
                   'sex': ['male', 'male', 'male', 'female', 'male']})
    
    df.loc[df.index[0], 'age'] = df.loc[df.index[-1], 'age']
    

    Cheers!!!