【问题标题】:pandas Series getting 'Data must be 1-dimensional' error熊猫系列得到“数据必须是一维”错误
【发布时间】:2021-09-16 06:13:09
【问题描述】:

我是 pandas 和 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 笔记本。

【问题讨论】:

  • 你能把你的进口包括进来吗……只是为了确保。因为这看起来应该有效。我刚刚用from pandas import Series; from numpy.random import randn 运行了你的代码,它工作得很好。
  • 我使用的是 from from from numpy.matlib import randn。当我更改为 numpy.random 时,它起作用了...谢谢!你知道我是否可以让 eclipse 得到正确的导入?
  • 我没用eclipse,没头绪。
  • 此外,我们总是感谢您对所有有用并提供良好信息的答案进行投票。

标签: python pandas numpy


【解决方案1】:

我怀疑你的导入有误。

如果您将其添加到您的代码中:

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)

【讨论】:

  • 嗯,我不确定使用from pandas import Series from numpy.random import randn 是否是好的解决方案。在我看来,使用import pandas as pd import numpy as np 会更好。你怎么看?
  • @jezrael 绝对!这只是确定问题所在。
  • 好的,所以我认为您可以将其添加到答案中 - 它有效,但不要使用它。 ;)
  • @jezrael 补充说,有趣的是 from pandas import DataFrame, Series 在 Wes 的书中 :-)
  • 是的,但是 here 它是 - 默认的 pandas 导入 ;)
【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-22
    • 2020-06-03
    • 1970-01-01
    • 2022-06-21
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    相关资源
    最近更新 更多