“TypeError:只能将长度为1的数组转换为Python标量”

时间:2013-03-25 22:58:04

标签: pandas

这似乎是我pandas.Series.all中的错误(df是Pandas DataFrame对象,pdpandas的简写:

In [18]: df.foo.apply(lambda x: x.startswith(u'bar').head()
Out[18]:
0    True
1    False
2    True
3    True
4    False
Name: foo

In [19]: (df.baz == u'frobozz').head()
Out[19]: 
0    False
1    False
2    True
3    True
4    False
Name: baz

In [20]: (type(Out[20]), type(Out[19]))
Out[20]: (pandas.core.series.Series, pandas.core.series.Series)

In [21]: pd.Series.all(Out[18], Out[19])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-310-d132f431d45f> in <module>()
----> 1 pd.Series.all(Out[18], Out[19])

/home/jones/.virtualenvs/proj/local/lib/python2.7/site-packages/pandas/core/series.pyc in f(self, *args, **kwargs)
    276     @Appender(func.__doc__)
    277     def f(self, *args, **kwargs):
--> 278         result = func(self, *args, **kwargs)
    279         if isinstance(result, np.ndarray) and result.ndim == 0:
    280             # return NumPy type

/home/jones/.virtualenvs/proj/local/lib/python2.7/site-packages/numpy/core/_methods.pyc in _all(a, axis, dtype, out, keepdims)
     28 def _all(a, axis=None, dtype=None, out=None, keepdims=False):
     29     return um.logical_and.reduce(a, axis=axis, dtype=dtype, out=out,
---> 30                                  keepdims=keepdims)                                                                                                                       
     31
     32 def _count_reduce_items(arr, axis):

TypeError: only length-1 arrays can be converted to Python scalars

发生了什么事?

2 个答案:

答案 0 :(得分:1)

从doc,pd.Series.all看来只带一个Series对象。试试这个 -

pd.Series.all(Out[18].append(Out[19]))

答案 1 :(得分:1)

这对我来说似乎不是一个错误,但我不知道你对pd.Series.all(Out[18], Out[19])的看法。

>>> pd.Series.all?
Type:       instancemethod
String Form:<unbound method Series.all>
File:       /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas-0.10.1-py2.7-macosx-10.6-intel.egg/pandas/core/series.py
Definition: pd.Series.all(self, *args, **kwargs)
Docstring:
a.all(axis=None, out=None)

Returns True if all elements evaluate to True.

您正在使用该类中的版本,因此第一个参数被解释为实例,第二个参数被解释为轴。 pandas正在尝试将您传递的第二个Series转换为整数以将其理解为轴,如果数组的长度为&gt;则无法使用该值。 1。