简体   繁体   English

如何将numpy数组转换为pandas数据框?

[英]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: 我有一个名为heart_rate的numpy数组,大小为(1181,),我尝试使用以下代码将其转换为熊猫数据框:

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

But I got the following error: 但我收到以下错误:

IndexError: too many indices for array IndexError:数组索引过多

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM