Comprehensive notes on dataframe iteration class 12 ip

In this article, I will provide you Comprehensive notes on dataframe iteration class 12 ip. So here we go!

Before start reading this chapter I would like to recommend you to read Data handling using pandas I (Creating Dataframes) and Importing/Exporting data between Dataframe and CSV file. In that chapter, you learnt how to create dataframes using different objects and import-export data from and to CSV files.

In this chapter, you will learn about Dataframe operations on Rows and Columns. I will cover the part which is mentioned in the syllabus as following:

  1. Pandas iterate over rows and columns
  2. Add row(s)
  3. Add column(s)

Dataframe iteration class 12 ip

So let’s start dataframe operations on rows and columns for the topic dataframe iteration class 12 IP. First, we will discuss iterate over data frame rows python.

How to iterate over dataframe?

There are few methods you can use for iterate over dataframe. For example by using for loop with functions such as <df>.iterrows() and <df>.iteritems(). 

Each and every element of dataframe is stored as a set of rows and a set of columns. Each row and column has its own index. So now the questions is How do you use Iterrows in Python? Let’s understand with python code for dataframe iteration class 12 IP:

import pandas as pd
def df_operations():
    sc_4yrs={2016:{'Virat Kohli':2595,'Rohit Sharma':2406,'Shikhar Dhawan':2378},
         2017:{'Virat Kohli':2818,'Rohit Sharma':2613,'Shikhar Dhawan':2295},
         2018:{'Virat Kohli':2595,'Rohit Sharma':2406,'Shikhar Dhawan':2378},
         2019:{'Virat Kohli':2595,'Rohit Sharma':2406,'Shikhar Dhawan':2378}}
    df=pd.DataFrame(sc_4yrs)
    print(df)
    print("------------------------------------------------------------------------")
    for i,row in df.iterrows():
        print(row)
df_operations() 
Output iterrows function dataframe iteration class 12 ip
Output iterrows function dataframe iteration class 12 ip

The iterrows() function iterate dataframe horizontally. In above program you can see that in for loop we have iterated the datafram with i and row variable. The variable ‘i’ extract dictionary names from the data frame so that won’t be printed in output. The variable ‘row’ extract dictionary key values, stored as runs scored here in the dictinary for each row.

Extracting data row-wise (printing with custom message)

import pandas as pd 
import pandas as pd
def df_operations():
    sc_4yrs={2016:{'Virat Kohli':2595,'Rohit Sharma':2406,'Shikhar Dhawan':2378},
         2017:{'Virat Kohli':2818,'Rohit Sharma':2613,'Shikhar Dhawan':2295},
         2018:{'Virat Kohli':2735,'Rohit Sharma':2406,'Shikhar Dhawan':2378},
         2019:{'Virat Kohli':2455,'Rohit Sharma':2310,'Shikhar Dhawan':1844}}
    df=pd.DataFrame(sc_4yrs)
    print(df)
    print("------------------------------------------------------------------------")
    for (r,rs) in df.iterrows():
        print("Player:",r)
        i=2016
        for v in rs:
            print("Runs in ",i,":",v)
            i=i+1
df_operations() 
Output 2 extract data row wise
Output 2 extract data row wise

In above code, custom message is added in front of data with the help of another for loop which iterates two other variables i.e. i and val, i for a simple increment of year values and val for values of each row.

Now in the next section of dataframe iteration class 12 ip, we will see how to use iteritems function?

Using iteritems() function

Observe this code where I have used iteritems() function:

import pandas as pd
def df_operations():
    sc_4yrs={2016:{'Virat Kohli':2595,'Rohit Sharma':2406,'Shikhar Dhawan':2378},
         2017:{'Virat Kohli':2818,'Rohit Sharma':2613,'Shikhar Dhawan':2295},
         2018:{'Virat Kohli':2735,'Rohit Sharma':2406,'Shikhar Dhawan':2378},
         2019:{'Virat Kohli':2455,'Rohit Sharma':2310,'Shikhar Dhawan':1844}}
    df=pd.DataFrame(sc_4yrs)
    print(df)
    print("------------------------------------------------------------------------")
    for (year,runs) in df.iteritems():
        print("Year:",year)
        print(runs)
df_operations() 
Output 3 how to use iteritems function
Output 3 how to use iteritems function

After understanding this let’s see how to add index, row or column into dataframe.

How to add index, row or column?

There certain ways to add index, row or column into the dataframe. Let’s we discuss these ways into the next section of dataframe iteration class 12 IP.

How to add index?

When you have created dataframe, you have an option to specify the index of your choice. If it’s not specified that time python assign default index to a dataframe starting with 0. If you have missed that you can add index by use set_index() function. This is actually changing index not adding any new index. Let’s try this in py-code:

import pandas as pd
def df_setindex():
    stu_XII={'Name':['Abhay','Bharat','Chandu','Dharmik','Ervin'],
             'Eng':[66,69,75,74,70],'Maths':[85,82,84,80,75],'IP':[95,82,63,84,90]}
    df=pd.DataFrame(stu_XII)
    print(df)
    df.set_index('Name',inplace=True)
    print(df) 
Output 4 add index

You can reset index anytime again using reset_index() method in same manner as set_index() is used.

How to add row(s)?

You can add single and multiple rows into dataframe using appendd method. So in this section of dataframe iteration class 12 IP.

Add single row using append() function?

Python allows append() function to insert new row in a dataframe. Look in this example:

import pandas as pd
def df_addRow():
    stu_XII={'Name':['Abhay','Bharat','Chandu','Dharmik','Ervin'],
             'Eng':[66,69,75,74,70],'Maths':[85,82,84,80,75],'IP':[95,82,63,84,90]}
    df=pd.DataFrame(stu_XII)
    df=df.append({'Name':'Firoz','Eng':76,'Maths':80,'IP':84},ignore_index=True)
    print(df)
df_addRow() 
Ouptut 5 Add single row into dataframe using append() method

Add mulitple rows using append() function?

Have a look at the following code:

import pandas as pd
def df_addRows():
    stu_XII={'Name':['Abhay','Bharat','Chandu','Dharmik','Ervin'],
             'Eng':[66,69,75,74,70],'Maths':[85,82,84,80,75],'IP':[95,82,63,84,90]}
    df=pd.DataFrame(stu_XII)
    l=[pd.Series(['Ganesh',61,60,58],index=df.columns),
       pd.Series(['Kanishka',78,87,65],index=df.columns),
       pd.Series(['Laxman',91,95,98],index=df.columns)]    
    df=df.append(l,ignore_index=True)
    print(df)
df_addRows() 
Output 6 Add multiple rows using append() method
Output 6 Add multiple rows using append() method

I above code you can observe three rows data added using series and append method.

Another way of adding row is using loc[],iloc[] and ix[] attributes.
loc[] attributes access specific index written between brackets.
Look this python code, here we have accessed 2nd element..

import pandas as pd
def df_setindex():
    stu_XII={'Name':['Abhay','Bharat','Chandu','Dharmik','Ervin'],
             'Eng':[66,69,75,74,70],'Maths':[85,82,84,80,75],'IP':[95,82,63,84,90]}
    df=pd.DataFrame(stu_XII)
    print(df.loc[1]) 
Output 7 add rows
Output 7 add rows

Add row(s) using loc[]

Observe this code:

import pandas as pd
def df_addRows():
    stu_XII={'Name':['Abhay','Bharat','Chandu','Dharmik','Ervin'],
             'Eng':[66,69,75,74,70],'Maths':[85,82,84,80,75],'IP':[95,82,63,84,90]}
    df=pd.DataFrame(stu_XII)
    df.loc[5]=['Manisha',67,89,45]
    df.loc[6]=['Hemant',77,88,66]
    print(df)
df_addRows() 
add row using loc
add row using loc

You can also add number of using iloc[] and ix[] in similar way as we have added rows using loc[].

Now in the next section of dataframe iteration class 12 IP, we will see how to add columns.

How to add column(s)?

To add columns there are certain methods you can follow. These methods are as following:

  1. Using Dictionaries
  2. Using list
  3. Using insert() function
  4. Using assign() function

Add column using a dictionary

Let’s have a look at this code:.

import pandas as pd
def df_addColumn():
    stu_XII={'Name':['Abhay','Bharat','Chandu','Dharmik','Ervin'],
             'Eng':[66,69,75,74,70],'Maths':[85,82,84,80,75],'IP':[95,82,63,84,90]}
    df=pd.DataFrame(stu_XII)
    city={'Bhuj':'Abhay','Mandvi':'Bharat','Gandhidham':'Chandu','Anjar':'Dharmik','Mundra':'Ervin'}
    df['Location']= city
    print(df)
df_addColumn() 
add column using dictionary
add column using dictionary

In the above code, a dictionary is used to insert a new column by assigning as keys of dataframe object values.

Add column using list

See this code:

import pandas as pd
def df_addColumn():
    stu_XII={'Name':['Abhay','Bharat','Chandu','Dharmik','Ervin'],
             'Eng':[66,69,75,74,70],'Maths':[85,82,84,80,75],'IP':[95,82,63,84,90]}
    df=pd.DataFrame(stu_XII)
    city=['Bhuj','Mandvi','Gandhidham','Anjar','Mundra']
    df['Location']= city
    print(df)
df_addColumn()

This is the simplest and easy way to insert a column in a dataframe.

Add column using insert() function

Just look at this code to understand how to use insert() function:

import pandas as pd
def df_addColumn():
    stu_XII={'Name':['Abhay','Bharat','Chandu','Dharmik','Ervin'],
             'Eng':[66,69,75,74,70],'Maths':[85,82,84,80,75],'IP':[95,82,63,84,90]}
    df=pd.DataFrame(stu_XII)
    df.insert(3,"Phy",[45,67,89,56,48],True]
    print(df)
df_addColumn()

This function allows to insert a column at your desired location. It accepts parameters such as column index, column header or column name and values. Observe the output yourself.

Add column using assign() function

The following code is demonstrating how to use assign() function:

import pandas as pd
def df_addColumn():
    stu_XII={'Name':['Abhay','Bharat','Chandu','Dharmik','Ervin'],
             'Eng':[66,69,75,74,70],'Maths':[85,82,84,80,75],'IP':[95,82,63,84,90]}
    df=pd.DataFrame(stu_XII)
    df2 = df.assign(city = ['Bhuj', 'Mandvi', 'Anjar', 'Ghandhidham','Mundra'])
    print(d2)
df_addColumn()

Dear reader, I hope you like this article dataframe iteration class 12 IP. In the next article, you will learn more about dataframes. If you have any doubt regarding the above topic dataframe iteration class 12 IP, kindly post a comment in the comment section.

Comment Your Views

%d bloggers like this: