【问题标题】:Assigning a date to a Pandas Series of floats为 Pandas 系列浮点数分配日期
【发布时间】:2019-05-30 08:52:26
【问题描述】:

我有一个包含一些 floatsnan 的系列,我正在尝试覆盖一些丢失的数据。

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)

请注意最后一行下面的奇怪错误,即使我能够在 print 语句中访问 'purchase_date'

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

很有趣,用数字替换 datetime 行效果很好

s['purchase_date'] = 21

【问题讨论】:

  • 问题是什么?为什么会出现这种行为或解决方案/解决方法?

标签: python pandas datetime series


【解决方案1】:

可以查看源代码

 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)

【讨论】:

    【解决方案2】:

    这是一个错误,将在下一版 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
    

    对应的 GitHub issue 见:https://github.com/pandas-dev/pandas/issues/23451

    【讨论】:

    • 似乎我解决了导致错误的正确行:-),感谢分享页面
    • 谢谢,我使用的是 0.23.4 版。
    猜你喜欢
    • 2018-08-16
    • 1970-01-01
    • 2022-07-22
    • 2019-01-08
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    相关资源
    最近更新 更多