【问题标题】:Why does Series.min(skipna=True) throws an error caused by na value?为什么 Series.min(skipna=True) 会抛出 na 值导致的错误?
【发布时间】:2020-05-17 20:59:09
【问题描述】:

我使用时间戳(具有混合 DST 值)。在 Pandas 1.0.0 中尝试过:

s = pd.Series(
    [pd.Timestamp('2020-02-01 11:35:44+01'),
    np.nan, # same result with pd.Timestamp('nat')
    pd.Timestamp('2019-04-13 12:10:20+02')])

请求 min() 或 max() 失败:

s.min(), s.max() # same result with s.min(skipna=True)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Anaconda\lib\site-packages\pandas\core\generic.py", line 11216, in stat_func
    f, name, axis=axis, skipna=skipna, numeric_only=numeric_only
  File "C:\Anaconda\lib\site-packages\pandas\core\series.py", line 3892, in _reduce
    return op(delegate, skipna=skipna, **kwds)
  File "C:\Anaconda\lib\site-packages\pandas\core\nanops.py", line 125, in f
    result = alt(values, axis=axis, skipna=skipna, **kwds)
  File "C:\Anaconda\lib\site-packages\pandas\core\nanops.py", line 837, in reduction
    result = getattr(values, meth)(axis)
  File "C:\Anaconda\lib\site-packages\numpy\core\_methods.py", line 34, in _amin
    return umr_minimum(a, axis, None, out, keepdims, initial, where)
TypeError: '<=' not supported between instances of 'Timestamp' and 'float'

解决方法:

s.loc[s.notna()].min(), s.loc[s.notna()].max()

(Timestamp('2019-04-13 12:10:20+0200', tz='pytz.FixedOffset(120)'), Timestamp('2020-02-01 11:35:44+0100', tz='pytz.FixedOffset(60)'))

我在这里缺少什么?是bug吗?

【问题讨论】:

    标签: pandas timestamp aggregate na


    【解决方案1】:

    我认为这里的问题是熊猫使用具有不同时区的系列(如对象),所以 maxmin 这里失败了。

    s = pd.Series(
        [pd.Timestamp('2020-02-01 11:35:44+01'),
        np.nan, # same result with pd.Timestamp('nat')
        pd.Timestamp('2019-04-13 12:10:20+02')])
    print (s)
    0    2020-02-01 11:35:44+01:00
    1                          NaN
    2    2019-04-13 12:10:20+02:00
    dtype: object
    

    因此,如果转换为日期时间(但不是混合时区),它工作得很好:

    print (pd.to_datetime(s, utc=True))
    0   2020-02-01 10:35:44+00:00
    1                         NaT
    2   2019-04-13 10:10:20+00:00
    dtype: datetime64[ns, UTC]
    
    print (pd.to_datetime(s, utc=True).max())
    2020-02-01 10:35:44+00:00
    

    如果需要不同的时区,另一种可能的解决方案是:

    print (s.dropna().max())
    2020-02-01 11:35:44+01:00
    

    【讨论】:

    • 我不明白为什么会发生错误。 “skipna”是否不适用于 dtype 对象或 nat 值?
    • @Redoute - 我认为这是错误,因为特殊值对象具有不同时区和缺失值的日期时间
    猜你喜欢
    • 2011-02-28
    • 2013-10-11
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    相关资源
    最近更新 更多