gpt4 book ai didi

python - pandas.Series 在应该返回一个元素时返回一个 Series

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:29 25 4
gpt4 key购买 nike

我在使用值为 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. 这是 pandas 中的错误吗?
  3. 是否有一个简单的解决方法,无论数据类型如何(例如,也适用于 dtype=int 的系列)?

我正在使用 pandas V0.13.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 的情况下,您可以调用属性 .values ,它将返回一个 numpy 数组,但这仅适用于 Series 返回,如果返回单个元素值将引发错误。

作为解决方法,如果您无法升级,则 get_value 起作用:

In [112]:

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

关于python - pandas.Series 在应该返回一个元素时返回一个 Series,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25884499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com