Question:

Write the output of the following code:

import pandas as pd
s1 = pd.Series ([1, 2, 3], index = ['a','b','c'])
s2 = pd.Series ([4, 5, 6], index = ['b','c','d'])
print (s1 + S2)

Show Hint

Pandas adds Series values by matching index labels. A label found in only one Series gives NaN, and the result becomes float.
Updated On: Oct 20, 2026
Show Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Step 1: Understand the code:
The code makes two Series, s1 and s2, with different index labels. It then adds them with the + operator.
The printed line says S2 with a capital S, but the variable made earlier is s2 in small letters. Python names are case sensitive, so S2 as typed would raise NameError: name 'S2' is not defined. The question clearly means s2, so we solve it for s1 + s2.

Step 2: Data in the two Series:
s1 has a = 1, b = 2, c = 3.
s2 has b = 4, c = 5, d = 6.

Step 3: Rule for adding two Series:
Pandas adds values that have the same index label.
If a label is present in only one Series, there is nothing to add to it, so the result for that label is NaN (not a number).
Because NaN is a float value, the whole result becomes float.

Step 4: Add label by label:
Label a: only in s1, so the result is NaN.
Label b: 2 + 4 = 6.0.
Label c: 3 + 5 = 8.0.
Label d: only in s2, so the result is NaN.
The labels come out in sorted order a, b, c, d.

Step 5: Output checked by running the code:
a    NaN
b    6.0
c    8.0
d    NaN
dtype: float64


Final Answer:
The output is the Series shown above. (If the capital S2 is typed literally, Python gives NameError instead.)
Was this answer helpful?
0
0