访问和删除 Pandas Series 中的元素
现在我们来了解如何访问或修改 Pandas Series 中的元素。Pandas Series 的一大优势是我们能够以很多不同的方式访问数据。我们可以通过在方括号 [ ] 内添加索引标签或数字索引访问元素,就像访问 NumPy ndarray 中的元素一样。因为我们可以使用数字索引,因此可以使用正整数从 Series 的开头访问数据,或使用负整数从末尾访问。因为我们可以通过多种方式访问元素,为了清晰地表明我们指代的是索引标签还是数字索引,Pandas Series 提供了两个属性 .loc
和 .iloc
,帮助我们清晰地表明指代哪种情况。属性 .loc
表示 位置,用于明确表明我们使用的是标签索引(也就是用前面的Data指引)。同样,属性 .iloc
表示_整型位置_,用于明确表明我们使用的是数字索引(也就是用后面的Index指引)。我们来看一些示例:
# We access elements in Groceries using index labels:
# We use a single index label
print('How many eggs do we need to buy:', groceries['eggs'])
print()
# we can access multiple index labels
print('Do we need milk and bread:\n', groceries[['milk', 'bread']])
print()
# we use loc to access multiple index labels
print('How many eggs and apples do we need to buy:\n', groceries.loc[['eggs', 'apples']])
print()
# We access elements in Groceries using numerical indices:
# we use multiple numerical indic