2

I have a data frame with a field named 'completed_date' and it has a bunch of dates that look like this: '1900-01-01'. How can I update all these dates to be '2019-01-01' only if the date is '1900-01-01'?

I tried this code.

df.loc[df['completed_date'] == '1900-01-01', 'completed_date'] = '2019-01-01'

I didn't get an error and it seemed to run fine, but when I look at the results, I still see a bunch of '1900-01-01' records in this field. Maybe there is a Pandas solution for this. Not sure. Any thoughts?

Ajax1234
  • 69,937
  • 8
  • 61
  • 102
ASH
  • 20,759
  • 19
  • 87
  • 200
  • what's `df.completed_date.dtype`? – tdy Apr 01 '21 at 23:37
  • if it's `object`, you can try the `str.replace()` method that Prune linked, though it's not clear to me why your current code didn't work (works for me locally). – tdy Apr 01 '21 at 23:48
  • The data type is object. I tried this: df.completed_date('1900-01-01', '2019-01-01') I got this result: TypeError: 'Series' object is not callable – ASH Apr 02 '21 at 16:35
  • That was a mistake; not I can't edit the comment. Anyway... The data type is object. I tried this: df['completed_date'] = df['completed_date'].replace('1900-01-01', '2019-01-01') Nothing was updated. What am I doing wrong here? – ASH Apr 02 '21 at 16:43
  • 1
    Maybe your dates have leading/trailing spaces. Try: `df['completed_date'] = df['completed_date'].str.strip().str.replace('1900-01-01', '2019-01-01')` – tdy Apr 02 '21 at 17:05
  • 1
    This ultimately worked for me: .astype(str).str.replace So...df['completed_date'] = df['completed_date'].astype(str).str.replace('1900-01-01', '2019-01-01') – ASH Apr 05 '21 at 16:59
  • 1
    Thanks for a point in the right direction here! – ASH Apr 05 '21 at 17:00

0 Answers0