0

I am trying do convert a datetime field to date in pandas.

My code

final_result['DATE_TO'] = pd.to_datetime(final_result['DATE_TO'], utc=True, dayfirst=True).dt.date

Warning Message from Python

/opt/app-root/lib/python3.6/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

Sampledata

final_result['DATE_TO_']
0      2020-01-26 10:07:02
1      2019-11-27 06:12:12
2      2019-12-11 08:00:08
3      2019-12-05 11:20:03
4      2019-12-07 04:50:10

How to fix this .

pankaj
  • 420
  • 1
  • 8
  • 26
  • I always get this error but mostly I ignore . Curious to learn how to fix this. – Rahul rajan Jan 16 '20 at 02:09
  • This is because a few lines up you probably do something like `final_result = final_result[some_slice]` or have something return a view (like `.drop_duplicates()`). The TLDR is to find where this occurs and then add a `.copy()` at the end to ensure you create a new object, not a view of another thing. – ALollz Jan 16 '20 at 02:11
  • @ALollz, It would helpful if you write this as answer with an example – sneha nair Jan 16 '20 at 02:13
  • @ALollz, I went through the reference question, I was not able to get jinx. Could post as answer below as this be helpful. – Rahul rajan Jan 16 '20 at 02:20
  • @AndyL, I have 10K records against which I need apply this logic. – pankaj Jan 16 '20 at 02:22
  • that's interesting. I tried on your sample and that exact command above to convert and assign back to original column or create a new column. Both work fine without any warning – Andy L. Jan 16 '20 at 02:29
  • You probably have something like `df = pd.DataFrame(...)`, and then do a view like `final_result = df[df["somecol"]==1]`, and lastly `final_result=pd.to_datetime(...)`? – Henry Yik Jan 16 '20 at 02:30
  • @AndyL, How do I do the same logic using `.loc` – pankaj Jan 16 '20 at 02:36
  • It's `final_result.loc[:, 'DATE_TO'] = ...`. However, I use your exact command above without any warning. Therefore, I think your `final_result` has been previous re-assigned to some sliced frame as ALollz and Henry say. – Andy L. Jan 16 '20 at 03:24

0 Answers0