Assigning a date to a Pandas Series of floats

Viewed 41

I have a series with some floats and nan and I am trying to overwrite some of the missing data.

from pandas.core.series import Series
from datetime import datetime

d = {'name': None, 'purchase_date': None, 'value': 195146.0}
s = Series(d)


print(s['purchase_date'])
s['purchase_date'] = datetime(2019,1,3)

Note the odd error below on the last line even though I was able to access 'purchase_date' in the print statement.

ValueError: ['p' 'u' 'r' 'c' 'h' 'a' 's' 'e' '_' 'd' 'a' 't' 'e'] not contained in the index
.

Interesting enough, replacing the datetime line with a number works fine

s['purchase_date'] = 21
2 Answers

This is a bug that will be fixed in the next release of pandas (0.24.0):

In [1]: from datetime import datetime
   ...: import pandas as pd

In [2]: pd.__version__
Out[2]: '0.24.0.dev0+1469.g0b45abbe2'

In [3]: d = {'name': None, 'purchase_date': None, 'value': 195146.0}

In [4]: s = pd.Series(d)

In [5]: s['purchase_date'] = datetime(2019,1,3)

In [6]: s
Out[6]:
name                             NaN
purchase_date    2019-01-03 00:00:00
value                         195146
dtype: object

For the corresponding GitHub issue, see: https://github.com/pandas-dev/pandas/issues/23451

May check with the source code

 if not isinstance(key, (list, Series, np.ndarray, Series)): # here it reconginezed the datetim.datetime object as list , so they do list(key)
            try:
                key = list(key)
            except Exception:
                key = [key]

Case why

list('purchase_date') #key
Out[142]: ['p', 'u', 'r', 'c', 'h', 'a', 's', 'e', '_', 'd', 'a', 't', 'e']

How to prevent

s.loc['purchase_date']=datetime(2019,1,3)
#or
s[['purchase_date']]=datetime(2019,1,3)
Related