我正在学习 Pandas 并试图理解切片。当我尝试使用列名进行切片时,一切都有意义。我的数据框如下所示:
area pop
California 423967 38332521
Florida 170312 19552860
Illinois 149995 12882135
New York 141297 19651127
Texas 695662 26448193
当我执行 data['area':'pop']
时,我希望两列都显示,因为我使用的是显式索引,并且切片的开始和结束都应该包含在内,但是结果是一个空数据框。
我还为 data['area':]
获得了一个空数据框。为什么这与在其他地方使用显式索引进行切片不同?
最佳答案
With DataFrame, slicing inside of [] slices the rows. This is provided largely as a convenience since it is such a common operation.
您得到一个空的 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'>
你想要的是
>> data.loc[:, 'area':'pop']
关于python - 按列名切片的 Pandas 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45225841/