2

I am receiving the following warning message when performing the following transformation of a date into a string:

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

I am doing the following:

Data['Date'] = Data['Date'].dt.strftime('%Y-%m-%d')
Cœur
  • 37,241
  • 25
  • 195
  • 267
MCM
  • 1,479
  • 2
  • 17
  • 22
  • It actually suggests you to `Try using .loc[row_indexer,col_indexer] = value instead` – Vitalii Strimbanu Jan 24 '17 at 19:53
  • @VitaliiStrimbanu, thanks but I tried `Data.loc['Date'] = Data['Date'].dt.strftime('%Y-%m-%d')`it is not working and I receive the following error message: **SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame** – MCM Jan 24 '17 at 19:57
  • See this: http://stackoverflow.com/questions/30132282/datetime-to-string-with-series-in-python-pandas – Chuck Jan 24 '17 at 20:02
  • You're going to have to use `.apply` and a lambda function out on your dataframe ala: http://stackoverflow.com/questions/19738169/convert-column-of-date-objects-in-pandas-dataframe-to-strings – Chuck Jan 24 '17 at 20:04
  • 1
    Try `Data.loc[:, 'Date'] = Data['Date'].dt.strftime('%Y-%m-%d')`. See more info in this [post](http://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas) – Parfait Jan 24 '17 at 20:04
  • It might be because pandas doesn't really know if `Data` is a view or a copy. You can [Check here](http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy) and hope it will help. – Vitalii Strimbanu Jan 24 '17 at 20:04
  • @Parfait, Thanks this is what I was looking for. – MCM Jan 24 '17 at 21:58
  • @VitaliiStrimbanu, Thanks That is what I was lookin for – MCM Jan 24 '17 at 21:58

1 Answers1

2

If you provide a sample of your code, I can amend this answer to be more specific to your requirements. If this answer is deemed superfluous to the answer given in the quoted question, let me know, and I'll delete it.

I should make it clear, the following is a near exact replication of the answer to this question here: datetime to string with series in python pandas.

For some data frame:

df = pandas.Series(['20010101', '20010331'])

0    20010101
1    20010331
dtype: object

# Convert to the format you need:

dates = pandas.to_datetime(A, format = '%Y-%m-%d')

0   2001-01-01
1   2001-03-31
dtype: datetime64[ns]

# Then to convert back, do:

df2 = dates.apply(lambda x: x.strftime('%Y-%m-%d'))

0    2001-01-01
1    2001-03-31
dtype: object
Community
  • 1
  • 1
Chuck
  • 3,664
  • 7
  • 42
  • 76
  • Thanks. The answers above helped. You can delete it if you want but it also helps for other problems. – MCM Jan 24 '17 at 22:00
  • Ok glad it helped, I'll leave it up. But @EdChum should know: this is down to you, I make no contention. – Chuck Jan 24 '17 at 22:01