KnowledgeBoat Logo
|
LoginJOIN NOW

Informatics Practices

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 ?

Python Pandas

2 Likes

Answer

  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

Working

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.

Answered By

1 Like


Related Questions