Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

replace first row value with last row value – python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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!!!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading