You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从以店铺名为索引的DataFrame提取店铺名及用iloc取首个店铺名

Pandas Index Retrieval Questions: Answers

Hey there! Let's work through your two questions about extracting store names (the index) from your Pandas DataFrame. First, a quick fix for your original code: string values like Surya, Pen need quotation marks—otherwise Python will throw an error thinking they're undefined variables. Here's the corrected version:

import pandas as pd

purchase_1 = pd.Series({'Name': 'Surya', 'Item Purchased': 'Pen', 'Cost': 22.50})
purchase_2 = pd.Series({'Name': 'Deepak', 'Item Purchased': 'book', 'Cost': 2.50})
purchase_3 = pd.Series({'Name': 'Mindaguditi', 'Item Purchased': 'chocolate', 'Cost': 5.00})
df = pd.DataFrame([purchase_1, purchase_2, purchase_3], index=['Store 1', 'Store 1', 'Store 2'])

Question 1: How to get all store names from the DataFrame?

Since the store names are set as the index of your DataFrame, you can directly access the index attribute:

# Get all store names (including duplicates)
all_store_names = df.index
print(all_store_names)
# Output: Index(['Store 1', 'Store 1', 'Store 2'], dtype='object')

If you want only unique store names (no duplicates), use unique() on the index:

unique_store_names = df.index.unique()
print(unique_store_names)
# Output: Index(['Store 1', 'Store 2'], dtype='object')

Question 2: How to get the first store name using the iloc attribute?

iloc is used for position-based indexing. To get the first store name, you can use either of these two readable methods:

  1. Access the index directly with iloc (Index objects support position-based indexing too):
first_store_name = df.index.iloc[0]
print(first_store_name)
# Output: 'Store 1'
  1. Retrieve the first row with iloc[0], then grab its name attribute (which maps to the row's index value):
first_store_name = df.iloc[0].name
print(first_store_name)
# Output: 'Store 1'

Either approach works—pick whichever fits your coding style better!


内容的提问来源于stack exchange,提问作者surya deepak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:36:07