2017-04-03 109 views
3

我是熊猫新手& numpy。我运行一个简单的程序熊猫系列越来越'数据必须一维'错误

labels = ['a','b','c','d','e'] 
s = Series(randn(5),index=labels) 
print(s) 

收到以下错误

s = Series(randn(5),index=labels) File "C:\Python27\lib\site-packages\pandas\core\series.py", line 243, in 
__init__ 
    raise_cast_failure=True) File "C:\Python27\lib\site-packages\pandas\core\series.py", line 2950, in 
_sanitize_array 
    raise Exception('Data must be 1-dimensional') Exception: Data must be 1-dimensional 

任何想法可能是这个问题?我正在尝试使用eclipse,而不是使用ipython笔记本。

+0

你可以包括你的进口...,以确保公正。因为这看起来应该起作用。我只是用'from pandas import Series'运行你的代码;从numpy.random导入randn'的 ,它工作得很好。 – piRSquared

+0

我使用从numpy.matlib导入randn。当我改为numpy.random它的工作......谢谢! 你知道吗,如果有反正我可以让月食得到正确的导入? –

+0

我不使用日食,我不知道。 – piRSquared

回答

2

我怀疑你有你的进口错误

如果您添加到您的代码

from pandas import Series 
from numpy.random import randn 

labels = ['a','b','c','d','e'] 
s = Series(randn(5),index=labels) 
print(s) 

a 0.895322 
b 0.949709 
c -0.502680 
d -0.511937 
e -1.550810 
dtype: float64 

它运行良好。

这就是说,正如@jezrael所指出的那样,导入模块而不是污染名称空间更好。

您的代码应该看起来像这样。

解决方案

import pandas as pd 
import numpy as np 

labels = ['a','b','c','d','e'] 
s = pd.Series(np.random.randn(5),index=labels) 
print(s) 
+0

这工作..谢谢 –

+0

嗯,我不知道如果一般是好的解决方案使用'从pandas进口系列 从numpy.random进口randn'。在我看来,更好地使用'import pandas作为pd import numpy as np'。你怎么看? – jezrael

+0

@jezrael绝对!这只是确定问题所在。 – piRSquared

2

看来你需要numpy.random.rand随机floatsnumpy.random.randint随机integers

import pandas as pd 
import numpy as np 

np.random.seed(100) 
labels = ['a','b','c','d','e'] 
s = pd.Series(np.random.randn(5),index=labels) 
print(s) 
a -1.749765 
b 0.342680 
c 1.153036 
d -0.252436 
e 0.981321 
dtype: float64 

np.random.seed(100) 
labels = ['a','b','c','d','e'] 
s = pd.Series(np.random.randint(10, size=5),index=labels) 
print(s) 
a 8 
b 8 
c 3 
d 7 
e 7 
dtype: int32