CBSE Class 12 Informatics Practices Question 17 of 40

Python Pandas — I — Question 19

Back to all questions
19
Question

Question 15(b)

From the DataFrames created in previous question, write code to display only rows 0 and 1 from DataFrames df, df1, and df2.

Solution
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.iloc[0:2])
print(df1.iloc[0:2])
print(df2.iloc[0:2])
Output
   one  two
a  1.0  1.0
b  2.0  2.0
   one  two
d  NaN  4.0
b  2.0  2.0
   two three
d  4.0   NaN
a  1.0   NaN
Answer

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
.
iloc
[
0
:
2
])
print
(
df1
.
iloc
[
0
:
2
])
print
(
df2
.
iloc
[
0
:
2
])
Output
one two
a 1.0 1.0
b 2.0 2.0
one two
d NaN 4.0
b 2.0 2.0
two three
d 4.0 NaN
a 1.0 NaN