2017-04-03 29 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