【问题标题】:Operations such as slicing will also slice the index?切片等操作也会对索引进行切片?
【发布时间】:2020-10-17 23:35:01
【问题描述】:

我已经阅读了熊猫文档中的以下句子:

"Series 的行为与 ndarray 非常相似,并且是 大多数 NumPy 函数。但是,切片等操作也会 切片索引。”

我不确定第二句话在说什么。不是给定的,它会切入索引吗?

【问题讨论】:

  • A pandas.Series 就像一维数组,但它也有一个 index 或“轴标签”。 ndarray 没有单独的“索引”属性。

标签: python pandas numpy series


【解决方案1】:

考虑以下代码:

import numpy as np
import pandas as pd

series = pd.Series([0,1,2,3,4,5,6])
array = series.to_numpy()

# Outputs 4, because that is element 2 of [2,3,4].
print(array[2:5][2]) 

# Outputs 2, because series[2:5] now has index [2,3,4], so the
# element with index 2 is still 2.
print(series[2:5][2]) 

由于对系列进行切片,除非您使用 .iloc,否则使用系列的索引,而 ndarray 没有索引,系列和 ndarray 的行为并不总是相似。

这也意味着,当使用 Series 作为输入时,旨在具有 ndarray 输入的代码可能会以意想不到的方式失败,或者产生意想不到的结果,除非代码确保它正在使用 ndarray。

【讨论】:

    猜你喜欢
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2018-11-22
    • 2017-06-22
    • 2020-02-27
    • 2021-11-20
    相关资源
    最近更新 更多