pandas.Series返回一个Series应该返回一个元素

时间:2014-09-17 07:15:02

标签: python numpy pandas

使用值为numpy数组的pandas.Series时,我遇到了以下奇怪的行为。

% s = pd.Series([5,2], index=[6,7])
%s.loc[6]
5  <-- returning a value of type corresponding to s.dtype, as expected

% s = pd.Series([np.arange(5), np.arange(2)], index=[6,7])
% s.loc[6]
6    0
6    1
6    2
6    3
6    4
dtype: int64  <-- returning a Series instead of a value of type np.array?!

% type(s.loc[6])
pandas.core.series.Series

如果以s[6]访问它,行为相同。

问题:

  1. 是否允许使用值为numpy数组的Series,或者我开始做些什么不好?
  2. 这是熊猫的错误​​吗?
  3. 是否有一个简单的解决方法,无论dtype如何都可以使用(例如,也适用于dtype = int的系列)?
  4. 我正在使用pandas V0.13.1

1 个答案:

答案 0 :(得分:1)

好的,这看起来像0.13.0中的一个错误,已修复0.14.1

In [110]:

s = pd.Series([np.arange(5), np.arange(2)], index=[6,7])
print(s.loc[6])
type(s.loc[6])

[0 1 2 3 4]
Out[110]:
numpy.ndarray

如果返回Series,您可以调用将返回numpy数组的属性.values,但这仅适用于返回Series并引发错误的情况如果返回单个元素值。

作为一种解决方法,如果您无法升级,则get_value可以正常工作:

In [112]:

s.get_value(6)
Out[112]:
array([0, 1, 2, 3, 4])
相关问题