gpt4 book ai didi

python - Series.index 与 Series.index.values

转载 作者:行者123 更新时间:2023-11-30 23:30:05 27 4
gpt4 key购买 nike

pandas series 有两个密切相关的属性:Series.indexSeries.index.values

这两个中的第一个返回某些 pandas 索引类型的当前索引。它是可变的,可用于更改系列的索引(一件好事)。

第二个返回一个numpy.ndarray。但是,它是不可变的,并且无论索引后续如何更改,都会保留原始索引值。

我的问题:不可变的Series.index.values的意图是什么?

编辑:

嗯。忽略这个问题 - 我不能重复我昨晚看到的 s.index.values 的令人困惑的行为。

最佳答案

几乎所有(Series、DataFrame、Panel、Index 对象的).values 属性都返回底层 numpy 数据。索引本身是围绕此数据的复杂包装,提供额外方便的功能,例如(取自 this answer 的示例数据帧):

>>> s = df['A']
>>> s.index
MultiIndex
[(u'one', 1), (u'one', 2), (u'one', 3), (u'two', 1), (u'two', 2), (u'two', 3)]
>>> s.index.values
array([('one', 1L), ('one', 2L), ('one', 3L), ('two', 1L), ('two', 2L),
('two', 3L)], dtype=object)
>>> s.index.get_indexer([('one',1), ('two', 2)])
array([0, 4])

例如,当您使用某些可迭代更新索引时,会在幕后创建一个新的 Index 对象:

>>> s.index = np.arange(6)
>>> s.index
Int64Index([0, 1, 2, 3, 4, 5], dtype=int64)
>>> s.index.get_indexer([0,4])
array([0, 4])
>>> s.index.values
array([0, 1, 2, 3, 4, 5], dtype=int64)

关于python - Series.index 与 Series.index.values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20839325/

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