首页 > 解决方案 > 位置索引

问题描述

这是一个数据框:

bacteria = pd.DataFrame(
    {
        'bacteria_counts': [632, 1638, 569, 115],
        'other_feature': [438, 833, 234, 298]
    },
    index=['Firmicutes', 'Proteobacteria', 'Actinobacteria', 'Bacteroidetes'])

在此处输入图像描述

这是一个问题,如果我使用bacteria[2:3],它会返回:

在此处输入图像描述

代表什么[2:3]?行和列?(刚开始学习位置索引)

标签: pythonpandasdataframeindexing

解决方案


使用 Pandas,一般的切片语法如下:

[start row: up to but not including row , start column: up to but not including column]

这就是为什么在您的情况下,看到您没有提供列参数,您只是获得了索引中第三项的行。事实上,如果不使用更高级的切片方法,如果您尝试使用当前策略选择列,您可能会得到回溯。

但是,大多数 pandas 切片都是使用 .iloc 和 .loc 进行的。你应该看看文档。https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html


推荐阅读