Q.Find the output of the following Python code : import pandas as pd com=pd.Series([45,12,15,200],index=['mouse','printer','webcam','keyboard']) print(com[1:3])
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →When slicing a Pandas Series with integer ranges like [1:3], Python performs positional indexing, meaning it selects elements based on their numerical position (0-indexed). The slice [1:3] includes elements at position 1 and position 2, but excludes the element at position 3. The output will be a new Series containing 'printer' (12) and 'webcam' (15).
A Pandas Series is a one-dimensional labeled array capable of holding any data type. Think of it as a column in a spreadsheet or a single list with an associated index for each item. This index can be default integer positions (0, 1, 2, ...) or custom labels (like 'mouse', 'printer').
The core concept here is slicing in Pandas Series, specifically how it behaves when you use integer ranges directly. Pandas offers two primary ways to access data:
- Label-based indexing: Using
.loc[]with the actual labels from the Series index. - Position-based indexing: Using
.iloc[]with integer positions (0-indexed).
When you use direct integer slicing, like com[1:3], without explicitly calling .loc or .iloc, Pandas defaults to position-based slicing. This means it treats the numbers 1 and 3 as positions within the Series, not as labels from the custom index.
A common pitfall is confusing label-based slicing with position-based slicing, especially when the custom index also consists of integers. When using direct integer slicing [start:end], Pandas always interprets start and end as positions. If you intend to slice by labels, you must use .loc[].
Let's break down the code step by step.
-
Series Creation:
The first line
com=pd.Series([45,12,15,200],index=['mouse','printer','webcam','keyboard'])creates a Pandas Series namedcom.This Series has:
- Values:
[45, 12, 15, 200] - Custom Index:
['mouse', 'printer', 'webcam', 'keyboard']
We can visualize this Series with its values and their corresponding positions and labels:
Position Label Value 0 'mouse' 45 1 'printer' 12 2 'webcam' 15 3 'keyboard' 200 - Values:
-
Slicing Operation:
The line
print(com[1:3])attempts to slice thecomSeries.Since
1and3are integers and we are not using.locor.iloc, this is interpreted as a positional slice.In Python slicing, the syntax
[start:end]means:- Include the element at the
startposition. …
- Include the element at the
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.