CBSE Class 12 Informatics Practices Question 127 of 167

Python Pandas — I — Question 17

Back to all questions
17
Question

Question 14

Given :

import pandas as pd
d = {'one' : pd.Series([1., 2., 3.], index = ['a', 'b', 'c']), 'two' : pd.Series([1., 2., 3., 4.], index = ['a', 'b', 'c', 'd'])} 
df = pd.DataFrame(d)
df1 = pd.DataFrame(d, index = ['d', 'b', 'a'])
df2 = pd.DataFrame(d, index = ['d', 'a'], columns = ['two', 'three'])
print(df) 
print(df1) 
print(df2)

What will Python show the result as if you execute above code ?

Answer
Output
  one  two
a  1.0  1.0
b  2.0  2.0
c  3.0  3.0
d  NaN  4.0
   one  two
d  NaN  4.0
b  2.0  2.0
a  1.0  1.0
   two three
d  4.0   NaN
a  1.0   NaN
Explanation

The given code creates three pandas DataFrames df, df1, and df2 using the same dictionary d with different index and column labels. The first DataFrame df is created using the dictionary d with index labels taken from the index of the Series objects in the dictionary. The resulting DataFrame has two columns 'one' and 'two' with index labels 'a', 'b', 'c', and 'd'. The values in the DataFrame are filled in accordance to the index and column labels. The second DataFrame df1 is created with the same dictionary d but with a custom index ['d', 'b', 'a']. The third DataFrame df2 is created with a custom index ['d', 'a'] and a custom column label ['two', 'three']. Since the dictionary d does not have a column label three, all its values are NaN (Not a Number), indicating missing data.