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
Create a DataFrame in Python from the given list :
[['Divya', 'HR', 95000], ['Mamta', 'Marketing', 97000], ['Payal', 'IT', 980000], ['Deepak', 'Sales', 79000]]
Also give appropriate column headings as shown below :
Name Department Salary 0 Divya HR 95000 1 Mamta Marketing 97000 2 Payal IT 980000 3 Deepak Sales 79000 Carefully observe the following code :
import pandas as pd Year1 = {'Q1': 5000, 'Q2': 8000, 'Q3': 12000, 'Q4': 18000} Year2 = {'A': 13000, 'B': 14000, 'C': 12000} totSales = {1: Year1, 2: Year2} df = pd.DataFrame(totSales) print(df)
Answer the following :
(i) List the index of the DataFrame df.
(ii) List the column names of DataFrame df.
From the DataFrames created in previous question, write code to display only row 'a' from DataFrames df, df1, and df2.
From the DataFrames created in previous question, write code to display only rows 0 and 1 from DataFrames df, df1, and df2.