Pandas按列名进行数据切片

2024-09-26 21:59:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习熊猫,并试图理解切片。当我尝试使用列名进行切片时,一切都有意义。我的数据框如下所示:

              area       pop
California  423967  38332521
Florida     170312  19552860
Illinois    149995  12882135
New York    141297  19651127
Texas       695662  26448193

当我做data['area':'pop']时,我希望这两列都显示出来,因为我使用显式索引,切片的开始和结束都应该包含在内,但结果是一个空的数据帧。在

我还得到data['area':]的空数据帧。为什么这与其他地方的显式索引切片不同?在


Tags: 数据newdata地方切片areapop意义
2条回答

根据documentation

With DataFrame, slicing inside of [] slices the rows. This is provided largely as a convenience since it is such a common operation.

您得到了一个空的数据帧,因为您的索引包含字符串,并且在那里找不到值'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'>

你想要的是

^{pr2}$

如果要获取这两列,请使用:

import pandas as pd

#data = pd.read_csv('data.csv', header = True)

all = data[['area','pop']]

以便您可以将列列表传递给[]以按顺序选择列。

类似地,要仅获得面积列,请使用:

^{pr2}$

现在,如果要获取列的值,请使用:

all = data[['area','pop']].values
area = df[['area']].values

all和{}将是numpy数组。在

相关问题 更多 >

    热门问题