Python 熊猫系列得到“数据必须是一维的”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43192626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:37:19  来源:igfitidea点击:

pandas Series getting 'Data must be 1-dimensional' error

pythonpandasnumpy

提问by R Syed

I'm new to pandas & numpy. I'm running a simple program

我是熊猫和麻木的新手。我正在运行一个简单的程序

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

getting the following error

收到以下错误

    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

Any idea what can be the issue? I'm trying this using eclipse, not using ipython notebook.

知道可能是什么问题吗?我正在尝试使用 eclipse,而不是使用 ipython notebook。

采纳答案by piRSquared

I suspect you have your imports wrong

我怀疑你的进口错了

If you add this to your code

如果您将此添加到您的代码中

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

It runs fine.

它运行良好。

That said, and as pointed out by @jezrael, it's better practice to import the the modules rather than pollute the namespace.

也就是说,正如@jezrael 所指出的,导入模块而不是污染命名空间是更好的做法。

Your code should look like this instead.

您的代码应该如下所示。

solution

解决方案

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)

回答by jezrael

It seems you need numpy.random.randfor random floatsor numpy.random.randintfor random integers:

似乎您需要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