为Pandas系列花车分配日期

时间:2019-01-03 18:26:32

标签: python pandas datetime series

我有一个包含一些SELECT documents.*, updates .status, updates.updated FROM documents LEFT JOIN (SELECT id_document, status, MAX(last_update) AS updated FROM states GROUP BY id_document) AS updates ON states.id = documents.id ORDER BY states.last_update floats的系列,我正在尝试覆盖一些丢失的数据。

nan

即使我能够在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) 语句中访问'purchase_date',也请注意最后一行下面的奇怪错误。

print

足够有趣,用数字代替ValueError: ['p' 'u' 'r' 'c' 'h' 'a' 's' 'e' '_' 'd' 'a' 't' 'e'] not contained in the index . 行会很好

datetime

2 个答案:

答案 0 :(得分:3)

此错误将在下一版熊猫(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

有关相应的GitHub问题,请参见:https://github.com/pandas-dev/pandas/issues/23451

答案 1 :(得分:2)

可以检查源代码

 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]

说明原因

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

如何预防

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