我正在学习熊猫,并试图理解切片。当我尝试使用列名称进行切片时,一切都应合理。我的数据框如下所示:
area pop
California 423967 38332521
Florida 170312 19552860
Illinois 149995 12882135
New York 141297 19651127
Texas 695662 26448193
Run Code Online (Sandbox Code Playgroud)
当我这样做时,data['area':'pop']我希望这两列都显示,因为我使用的是显式索引,并且切片的开始和结尾都应包含在内,但结果是一个空的数据框。
我也得到了一个空的数据框data['area':]。为什么这与在其他地方使用显式索引切片不同?
根据文件
使用DataFrame时,在[]内切片可对行进行切片。由于这是一种常见的操作,因此很大程度上是为了方便而提供。
您会得到一个空的DataFrame,因为您的索引包含字符串,并且无法在其中找到值“ area”和“ pop”。这是数字索引的情况
>> data.reset_index()['area':'pop']
TypeError: cannot do slice indexing on <class 'pandas.core.indexes.range.RangeIndex'> with these indexers [area] of <class 'str'>
Run Code Online (Sandbox Code Playgroud)
您想要的是
>> data.loc[:, 'area':'pop']
Run Code Online (Sandbox Code Playgroud)