gerscorpion
gerscorpion

Reputation: 188

Python numpy 'too many indices for array'

I want to fill a two-dimensional array with series from a data frame call. When I execute the following code, I get the error 'too many indices for array'. When I manually set the shape to the series size, it suddenly switches to be a one position bigger. (The series are around 356 positions)

size_arr = np.empty(shape=(len(business_date_list)))
y_arr = np.empty(shape=(len(business_date_list)))

for i in range(0, len(business_date_list)):
    news = model_data['size'].loc[(model_data['date'] == business_date_list[i])]
    size_arr[i,:] = news
    newy = model_data['changeday'].loc[(model_data['date'] == business_date_list[i])]
    y_arr[i,:] = newy

Upvotes: 0

Views: 5083

Answers (2)

gerscorpion
gerscorpion

Reputation: 188

The indexing wasn't the problem but adapting the size correctly

shape = ((len(business_date_list)),500)
size_arr = np.empty(shape=(shape))
y_arr = np.empty(shape=(shape))
news = np.empty(shape=(500))
#newy = np.empty(shape=(500,))

for b in range(0, len(business_date_list)):
    news = model_data['size'].loc[(model_data['date'] == business_date_list[b])]
    c = 500-len(news)
    news = np.pad(news, (0,c), 'empty')
    size_arr[b,:] = news
    
    newy = model_data['changeday'].loc[(model_data['date'] == business_date_list[b])]
    d = 500-len(newy)    
    newy = np.pad(newy, (0,d), 'empty')
    y_arr[b,:] = newy

Upvotes: 0

hpaulj
hpaulj

Reputation: 231665

This reproduces your error message. You should have shown the full message, including the traceback. It has valuable information - for you and us!

In [332]: np.empty(3)[0,:]                                                      
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-332-c37e54b88567> in <module>
----> 1 np.empty(3)[0,:]

IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

You define a 1d array with

size_arr = np.empty(shape=(len(business_date_list)))

and try to index it as 2d with

size_arr[i,:] = news

Upvotes: 2

Related Questions