Pandas dataframe: ValueError: num должно быть 1
Я получаю следующую ошибку, когда я пытаюсь участка pandas dataframe
:
ValueError: num должен быть 1
код:
import matplotlib.pyplot as plt
names = ['buying', 'maint', 'doors', 'persons', 'lug_boot', 'safety']
custom = pd.DataFrame(x_train) //only a portion of the csv
custom.columns = names
custom.hist()
plt.show()
Я попытался снова прочитать файл из csv
и я получаю ту же самую ошибку.
Edit:
print x_train
выход:
[[0.0 0.0 0.0 0.0 0.0 0.0]
[0.0 1.0 1.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.3333333333333333 0.3333333333333333 2.0 2.0 2.0 2.0]
[0.0 0.0 3.0 3.0 3.0 3.0]]
Edit2:
полный список ошибок (Traceback):
Traceback (последний звонок):
файл "temp.py", строка 104, in традиция.dropna().hist ()
"/home/kostas/anaconda2/lib/python2.7/site-packages/pandas/tools/plotting.py", строка 2893, в hist_frame layout=макет)файл "/home/kostas/anaconda2/lib/python2.7/site-packages/pandas/tools/plotting.py", строка 3380, in _subplots ax0 = фиг.add_subplot (nrows, ncols, 1, **subplot_kw)
файл "/home/kostas/anaconda2/lib/python2.7/site-packages/matplotlib/figure.py", строка 1005, в add_subplot a = subplot_class_factory (projection_class) (self, * args, * * kwargs)
файл "/home/kostas/anaconda2/lib/python2.7/site-packages/matplotlib/axes/_subplots.py", строка 64, в init maxn=rows * cols, num=num))
2 ответов
поэтому я уверен, что ваша проблема связана с форматом массива train_x. Я попробовал вашу программу с массивом 10,000 строк и 6 cols, и она работала нормально, поэтому проблема не в размере. По какой-то причине один из len(x_train)
или len(x_train[0])
равен 0. Что заставляет меня думать так:
ValueError вы получаете от matplotlib.ось.Модуль _subplot, который имеет дело с рисованием многих небольших подзаголовков в большом графике (поэтому каждая небольшая гистограмма). Код модуля это:
"""
*rows*, *cols*, *num* are arguments where
the array of subplots in the figure has dimensions *rows*,
*cols*, and where *num* is the number of the subplot
being created. *num* starts at 1 in the upper left
corner and increases to the right.
"""
rows, cols, num = args
rows = int(rows)
cols = int(cols)
if isinstance(num, tuple) and len(num) == 2:
num = [int(n) for n in num]
self._subplotspec = GridSpec(rows, cols)[num[0] - 1:num[1]]
else:
if num < 1 or num > rows*cols:
raise ValueError(
"num must be 1 <= num <= {maxn}, not {num}".format(
maxn=rows*cols, num=num))
ваша проблема в этой части (см. пояснения в комментариях в коде):
if num < 1 or num > rows*cols:
# maxN is the number of rows*cols and since this is showing 0 for you (in your error stacktrace),
# it means the number of cols being passed into your histogram is 0. Don't know why though :P
raise ValueError(
"num must be 1 <= num <= {maxn}, not {num}".format(
maxn=rows*cols, num=num))
Я не знаю, как Вы читаете свой формат ввода, но я уверен, что проблема связана с ним. Если вы установите x_train на это, он отлично работает:
x_train = [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
[1.0, 1.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.3333333333333333, 0.3333333333333333, 2.0, 2.0, 2.0, 2.0],
[0.0, 0.0, 3.0, 3.0, 3.0, 3.0]]
попробуйте сделать это перед вызовом кода в вашем вопросе и посмотреть, работает ли это:
x_train = list([list(x) for x in x_train])
У меня была та же проблема, и я обнаружил, что это связано с тем, что массив NumPy был массивом объектов, а не массивом float.
попробуйте это:
x_train = x_train.astype(np.float)