Niam45
Niam45

Reputation: 578

How can I convert my numpy array into a pandas dataframe?

I have a numpy array called heart_rate with size (1181,) I tried to convert it into a pandas dataframe using the following code:

dataset = pd.DataFrame({'Column 1':heart_rate[:,0]})

But I got the following error:

IndexError: too many indices for array

Upvotes: 0

Views: 58

Answers (1)

EdChum
EdChum

Reputation: 393933

Just do:

dataset = pd.DataFrame({'Column 1':heart_rate})

or

dataset = pd.DataFrame(heart_rate, columns=['Column 1'])

your error is that you're trying to slice the array with too many indexers, it's a 1-D array

example:

In[2]:
heart_rate = np.arange(1,10)
heart_rate.shape

Out[2]: (9,)


In[3]:
df = pd.DataFrame(heart_rate, columns=['Column 1'])
df

Out[3]: 
   Column 1
0         1
1         2
2         3
3         4
4         5
5         6
6         7
7         8
8         9

and

In[4]:
df = pd.DataFrame({'Column 1':heart_rate})
df

Out[4]: 
   Column 1
0         1
1         2
2         3
3         4
4         5
5         6
6         7
7         8
8         9

Here you can see that it's your slicing that is generating the error:

heart_rate[:,0]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-5-e1eba9de0086> in <module>()
----> 1 heart_rate[:,0]

IndexError: too many indices for array

Upvotes: 1

Related Questions