如何从以店铺名为索引的DataFrame提取店铺名及用iloc取首个店铺名
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:
- 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'
- Retrieve the first row with
iloc[0], then grab itsnameattribute (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

