You are on page 1of 2

import pandas as pd

df=pd.DataFrame({'Name':['Anil','Subhash','Simoni','Sneha','Dhruv','Anil'],
'Age':[12,14,15,16,13,16],
'Class':[10,11,12,11,9,10],
'Div':['vega','antares','rigel','deneb','vega','sirius'],
'house':['red','blue','yellow','blue','green','red']
})
print(df)
# loc() prints all the rows inclusive of the index specified
print(df.loc[2:4])
# iloc() prints from the row specifieds to the end-1 row
print(df.iloc[2:4])
# to print specific columns use []
print(df.loc[1:3,['Name','Class']])
# we cannot specify label with iloc[] but with loc we can
print(df.iloc[1:3,['Name','Class']])
use loc[]to print specific row and columns
print(df.loc[[1,3],['Name','Div']])

OUTPUT:

Name Age Class Div house


0 Anil 12 10 vega red
1 Subhash 14 11 antares blue
2 Simoni 15 12 rigel yellow
3 Sneha 16 11 deneb blue
4 Dhruv 13 9 vega green
5 Anil 16 10 sirius red
================================
Name Age Class Div house
2 Simoni 15 12 rigel yellow
3 Sneha 16 11 deneb blue
4 Dhruv 13 9 vega green
=============================
Name Age Class Div house
2 Simoni 15 12 rigel yellow
3 Sneha 16 11 deneb blue
===============================
Name Class
1 Subhash 11
2 Simoni 12
3 Sneha 11
=================================
Traceback (most recent call last):
File "<string>", line 15, in <module>
File "/usr/local/lib/python3.8/dist-packages/pandas/core/indexing.py", line 925, in __getitem__
return self._getitem_tuple(key)
File "/usr/local/lib/python3.8/dist-packages/pandas/core/indexing.py", line 1506, in
_getitem_tuple
self._has_valid_tuple(tup)
File "/usr/local/lib/python3.8/dist-packages/pandas/core/indexing.py", line 754, in
_has_valid_tuple
self._validate_key(k, i)
File "/usr/local/lib/python3.8/dist-packages/pandas/core/indexing.py", line 1420, in
_validate_key
raise IndexError(f".iloc requires numeric indexers, got {arr}")
IndexError: .iloc requires numeric indexers, got ['Name' 'Class']
>
==============================================================
Name Div
1 Subhash antares
3 Sneha deneb

You might also like