Python Selecting Data From Pandas DataFrame Using Loc And Iloc














































Python Selecting Data From Pandas DataFrame Using Loc And Iloc



Description:


Indexing in pandas means simply selecting particular rows and columns of data from a DataFrame. Indexing could mean selecting all the rows and some of the columns, some of the rows and all of the columns, or some of each of the rows and columns. 


In pandas you can select a column and return column with label col as Series or a few columns and return columns as a new DataFrame. You can also use loc and iloc to perform just about any data selection operation. Loc is label-based, which means that you have to specify rows and columns based on their row and column labels. iloc is integer index based, so you have to specify rows and columns by their integer index.


In our program below we%u2019ll first create a Pandas DataFrame and after that we will,


  1. Select data using loc.
  2. Select data using iloc.



Program:


#! /usr/bin/env python3


# Dictionary

dictionary = {"country": ["Brazil", "Russia", "India", "China", "South Africa"],


       "capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", "Pretoria"],


       "population": [200.4, 143.5, 1252, 1357, 52.98] }


# Import pandas library 

import pandas as pd


# Converting Dictionary to DataFrame and saving it in a variable df 

df = pd.DataFrame(dictionary)

# Print df  

print(df)



Using loc:

#! /usr/bin/env python3


# Dictionary

dictionary = {"country": ["Brazil""Russia""India""China""South Africa"],


       "capital": ["Brasilia""Moscow""New Dehli""Beijing""Pretoria"],


       "population": [200.4143.51252135752.98] }


# Import pandas library 

import pandas as pd


# Converting Dictionary to DataFrame and saving it in a variable df 

df = pd.DataFrame(dictionary)


# Print df  using loc

print(df.loc[:,'capital'])


Using iloc:

#! /usr/bin/env python3


# Dictionary

dictionary = {"country": ["Brazil""Russia""India""China""South Africa"],


       "capital": ["Brasilia""Moscow""New Dehli""Beijing""Pretoria"],


       "population": [200.4143.51252135752.98] }


# Import pandas library 

import pandas as pd


# Converting Dictionary to DataFrame and saving it in a variable df 

df = pd.DataFrame(dictionary)


# Print df  using iloc

print(df.iloc[:,0])