Как исправить 'ValueError: массив нулевого размера для операции сокращения fmin, которая не имеет идентичности' - PullRequest
0 голосов
/ 11 апреля 2019

Я пытаюсь построить несколько простых временных рядов, и обычно они работают нормально, но этот особый случай не дает ожидаемых результатов:

Я запускаю код в Visual Studio и CLI, где я получил то же сообщение об ошибке. Но когда я попытался запустить тот же код в ноутбуке Jupyter, где я получил три ячейки (CELL1, CELL2 и CELL3 разделены), весь код работает нормально. Только когда я помещал CELL2 и CELL3 в одну единственную ячейку, это снова вызывало типичную ошибку.

# CELL 1
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import datetime
from pandas import Series
import sys 

input_array = np.array([[0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.]])

date_list = [datetime.date(2019, 1, 2), datetime.date(2019, 1, 9), datetime.date(2019, 1, 16), datetime.date(2019, 1, 23), datetime.date(2019, 1, 30), datetime.date(2019, 2, 6), datetime.date(2019, 2, 13), datetime.date(2019, 2, 20), datetime.date(2019, 2, 27), datetime.date(2019, 3, 6), datetime.date(2019, 3, 13), datetime.date(2019, 3, 20), datetime.date(2019, 3, 27), datetime.date(2019, 4, 3), datetime.date(2019, 4, 10)]

def get_indiv_series(table, index):
    out_series = []
    for i in table:
        out_series.append(i[index])
    return out_series

def make_indiv_category_plot(times, table, index, axis):
    print(get_indiv_series(table, index))
    series = Series(get_indiv_series(table, index), index=times)
    try:
        series.plot(style='-', ax=axis)    
    except ValueError as err:
        print(' A value Error ocurred')
        print(index)
        print(series)
        print(get_indiv_series(table, index))
        print(sys.exc_info())
        raise err
    line_i, = plt.plot([])
    return line_i
# CELL 2
fig = plt.figure(figsize=(10, 10))
ax = plt.gca()
# CELL 3
line_0 = make_indiv_category_plot(date_list, input_array, 0, ax)
line_1 = make_indiv_category_plot(date_list, input_array, 1, ax)
line_2 = make_indiv_category_plot(date_list, input_array, 2, ax)
line_3 = make_indiv_category_plot(date_list, input_array, 3, ax)
line_4 = make_indiv_category_plot(date_list, input_array, 4, ax)

РЕЗУЛЬТАТЫ (объединение CELL2 и CELL 3):

[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
2019-01-02    0.0
2019-01-09    0.0
2019-01-16    0.0
2019-01-23    0.0
2019-01-30    0.0
2019-02-06    0.0
2019-02-13    0.0
2019-02-20    0.0
2019-02-27    0.0
2019-03-06    0.0
2019-03-13    0.0
2019-03-20    0.0
2019-03-27    0.0
2019-04-03    0.0
2019-04-10    0.0
dtype: float64
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
2019-01-02    0.0
2019-01-09    0.0
2019-01-16    0.0
2019-01-23    0.0
2019-01-30    0.0
2019-02-06    0.0
2019-02-13    0.0
2019-02-20    0.0
2019-02-27    0.0
2019-03-06    0.0
2019-03-13    0.0
2019-03-20    0.0
2019-03-27    0.0
2019-04-03    0.0
2019-04-10    0.0
dtype: float64
 A value Error ocurred
1
2019-01-02    0.0
2019-01-09    0.0
2019-01-16    0.0
2019-01-23    0.0
2019-01-30    0.0
2019-02-06    0.0
2019-02-13    0.0
2019-02-20    0.0
2019-02-27    0.0
2019-03-06    0.0
2019-03-13    0.0
2019-03-20    0.0
2019-03-27    0.0
2019-04-03    0.0
2019-04-10    0.0
dtype: float64
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
(<class 'ValueError'>, ValueError('zero-size array to reduction operation fmin which has no identity',), <traceback object at 0x000001DB4550C208>)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-814d54a9ca4b> in <module>()
      5 line_0 = make_indiv_category_plot(date_list, input_array, 0, ax)
      6 
----> 7 line_1 = make_indiv_category_plot(date_list, input_array, 1, ax)
      8 
      9 line_2 = make_indiv_category_plot(date_list, input_array, 2, ax)

<ipython-input-3-ddbd896b3735> in make_indiv_category_plot(times, table, index, axis)
     57         print(get_indiv_series(table, index))
     58         print(sys.exc_info())
---> 59         raise err
     60     # create a empty line with the same properties as the time series for legends
     61     line_i, = plt.plot([])#, color='%s'%db_fplive.Get_color_table()[index+1], label=db_fplive.Get_label_table()[index+1])

<ipython-input-3-ddbd896b3735> in make_indiv_category_plot(times, table, index, axis)
     48     # plot the series with the color and label from the category dictionaries
     49     try:
---> 50         series.plot()#style='-', ax=axis, color='%s'%db_fplive.Get_color_table()[index+1], label=db_fplive.Get_label_table()[index+1])
     51     except ValueError as err:
     52         print(' A value Error ocurred')

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pandas\plotting\_core.py in __call__(self, kind, ax, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, label, secondary_y, **kwds)
   2740                            colormap=colormap, table=table, yerr=yerr,
   2741                            xerr=xerr, label=label, secondary_y=secondary_y,
-> 2742                            **kwds)
   2743     __call__.__doc__ = plot_series.__doc__
   2744 

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pandas\plotting\_core.py in plot_series(data, kind, ax, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, label, secondary_y, **kwds)
   1996                  yerr=yerr, xerr=xerr,
   1997                  label=label, secondary_y=secondary_y,
-> 1998                  **kwds)
   1999 
   2000 

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pandas\plotting\_core.py in _plot(data, x, y, subplots, ax, kind, **kwds)
   1799         plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds)
   1800 
-> 1801     plot_obj.generate()
   1802     plot_obj.draw()
   1803     return plot_obj.result

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pandas\plotting\_core.py in generate(self)
    249         self._compute_plot_data()
    250         self._setup_subplots()
--> 251         self._make_plot()
    252         self._add_table()
    253         self._make_legend()

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pandas\plotting\_core.py in _make_plot(self)
    998 
    999             lines = _get_all_lines(ax)
-> 1000             left, right = _get_xlim(lines)
   1001             ax.set_xlim(left, right)
   1002 

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\pandas\plotting\_tools.py in _get_xlim(lines)
    362     for l in lines:
    363         x = l.get_xdata(orig=False)
--> 364         left = min(np.nanmin(x), left)
    365         right = max(np.nanmax(x), right)
    366     return left, right

C:\Program Files (x86)\Microsoft Visual Studio\Shared\Anaconda3_64\lib\site-packages\numpy\lib\nanfunctions.py in nanmin(a, axis, out, keepdims)
    278         # Fast, but not safe for subclasses of ndarray, or object arrays,
    279         # which do not implement isnan (gh-9009), or fmin correctly (gh-8975)
--> 280         res = np.fmin.reduce(a, axis=axis, out=out, **kwargs)
    281         if np.isnan(res).any():
    282             warnings.warn("All-NaN slice encountered", RuntimeWarning, stacklevel=2)

ValueError: zero-size array to reduction operation fmin which has no identity

Кто-нибудь знает, как решить проблему, или знаком с этим сообщением об ошибке?

1 Ответ

0 голосов
/ 12 апреля 2019

Хорошо, пока что я нашел решение, чтобы заставить код работать:

превратить созданный объект Series в объект DataFrame с одним столбцом (внутреннее представление которого по-прежнему должно быть объектом Series)

Подводя итог, магически работает следующий код:

# CELL 1
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import datetime
from pandas import Series
import sys 

input_array = np.array([[0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0.]])

date_list = [datetime.date(2019, 1, 2), datetime.date(2019, 1, 9), datetime.date(2019, 1, 16), datetime.date(2019, 1, 23), datetime.date(2019, 1, 30), datetime.date(2019, 2, 6), datetime.date(2019, 2, 13), datetime.date(2019, 2, 20), datetime.date(2019, 2, 27), datetime.date(2019, 3, 6), datetime.date(2019, 3, 13), datetime.date(2019, 3, 20), datetime.date(2019, 3, 27), datetime.date(2019, 4, 3), datetime.date(2019, 4, 10)]

def get_indiv_series(table, index):
    out_series = []
    for i in table:
        out_series.append(i[index])
    return out_series

def make_indiv_category_plot(times, table, index, axis):
    print(get_indiv_series(table, index))
    series = pd.DataFrame(get_indiv_series(table, index), index=times)
    try:
        series.plot(style='-', use_index = True)    
    except ValueError as err:
        print(' A value Error ocurred')
        print(index)
        print(series)
        print(get_indiv_series(table, index))
        print(sys.exc_info())
        raise err
    line_i, = plt.plot([])
    return line_i

fig = plt.figure(figsize=(10, 10))
ax = plt.gca()

line_0 = make_indiv_category_plot(date_list, input_array, 0, ax)
line_1 = make_indiv_category_plot(date_list, input_array, 1, ax)
line_2 = make_indiv_category_plot(date_list, input_array, 2, ax)
line_3 = make_indiv_category_plot(date_list, input_array, 3, ax)
line_4 = make_indiv_category_plot(date_list, input_array, 4, ax)

У кого-нибудь есть объяснение этому странному поведению?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...