Python

Break keyword – Explained with Examples

Python: Break keyword – Explained with Examples

Break Keyword:

The break statement ends the loop that contains it. Control of the programme is transferred to the statement immediately following the body of the loop.

If the break statement is within a nested loop (a loop within another loop), it will terminate the innermost loop.

Break keyword in Python

We can use break keyword in loops such as while loop and for loop as given below.

1)While loop with break keyword

It can cause a while loop to stop in the middle, even if the condition in the “while statement” remains True.

When the interpreter encounters a break statement, it stops the current loop execution and jumps directly to the code following the loop block.

Example:

Let us use break keyword in while loop .

Let us print all even elements from 1 to n till the number is not divisible by 5.

Below is the implementation:

# given n
n = 100
x = 1
# Using while to iterate till n
while(x <= n):
    # if the x is divisible by 5 then break the loop
    if(x % 5 == 0):
        break
    else:
        print(x)
        # increment the x
        x += 1
print("Break keyword is succesfully executed")

Output:

1
2
3
4
Break keyword is succesfully executed

Explanation:

In the preceding example, the condition in a while statement is True. Because the condition in the ‘while statement’ is always True, this type of loop will iterate over a set of statements indefinitely. We used a break statement to end this loop.

We are printing the value of x and then incrementing it by one in the loop block. Then it determines whether or not x is divisible by 5. When x is divisible by 5, the break statement is invoked. This ends the loop, and control is returned at the end of the while loop.

2)For loop with break Keyword

Example:

Let us use break keyword in for loop .

Given a list and print elements of list till the element of list is not divisible by 2.

Below is the implementation:

# given list
given_list = [4, 2, 8, 4, 1, 3, 7]
# Traverse the list using for loop
for i in range(len(given_list)):
    # if the element is not divisible by 2 then break the loop
    if(given_list[i] % 2 != 0):
        break
    else:
        print(given_list[i])
print("Break keyword executed successfully")

Output:

4
2
8
4
Break keyword executed successfully

Python: Break keyword – Explained with Examples Read More »

Convert Dictionary keys to a List

Convert Dictionary keys to a List in Python

In Python, dictionaries are useful data structures that use keys for indexing. They are an unordered sequence of items (key-value pairs), so the order does not matter. The keys are not able to be changed. Dictionaries, like lists, can hold a variety of data types, including integers, floats, strings, NaN, Booleans, lists, arrays, and even nested dictionaries.

Given a dictionary ,the task is to convert keys of dictionary to a list.

Examples:

Input:

dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}

Output:

list of keys :  ['Hello', 'world', 'BTechGeeks']

Convert Dictionary keys to a List

There are several ways to convert dictionary keys to a list some of them are:

Method #1:Using list()

A dictionary object is also an iterable object in Python, allowing you to iterate over all of the dictionary’s keys.

In Python, there is a member function called dict.keys that is part of the dictionary class ()

It returns a view object or an iterator that loops through the dictionary’s keys. This object can be used to iterate over existing lists or to create new ones.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# convert given_dictionary keys  to list
list_of_keys = list(dictionary.keys())
# print the converted list
print("list of keys : ", list_of_keys)

Output:

list of keys :  ['Hello', 'world', 'BTechGeeks']

Method #2:Using List Comprehension

The dictionary class in Python has a function keys() that returns an iterable sequence (dict keys) of all keys in the dictionary. Using the sequence returned by keys(), we can use the list comprehension to iterate over all keysin the dictionary and create a list of keys.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# convert given_dictionary keys  to list using list comprehension
list_of_keys = [key for key in dictionary.keys()]
# print the converted list
print("list of keys : ", list_of_keys)

Output:

list of keys :  ['Hello', 'world', 'BTechGeeks']

Method #3 :Using unpacking

Unpacking * works for any iterable object, so it is simple to create a list by using it in a list literal because dictionaries return their keys when iterated through.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# convert given_dictionary keys  to list using args function
list_of_keys = [*dictionary]
# print the converted list
print("list of keys : ", list_of_keys)

Output:

list of keys :  ['Hello', 'world', 'BTechGeeks']

Method #4:Converting only specified keys to list

Assume we want to convert only a subset of the keys in a dictionary to a list. For example, create a list of only the keys in the dictionary with values greater than 500. To accomplish this, we can use an if condition to iterate over pairs of dictionary keys and select only those keys where the condition returns True.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# convert specified given_dictionary keys to list
list_of_keys = [key for key in dictionary.keys() if dictionary[key] > 500]
# print the converted list
print("list of keys : ", list_of_keys)

Output:

list of keys :  ['Hello', 'BTechGeeks']

 
Related Programs:

Convert Dictionary keys to a List in Python Read More »

Convert String to Integer

Python: Convert String to Integer

String:

String is an immutable sequence data type in Python. It’s a string of Unicode characters enclosed by single, double, or triple quotes.

Given a string , the task is to convert the given string to integer.

Convert String to Integer in Python

1)int() function

The int() function returns an integer number from the specified value.

If no arguments are provided, the int() function returns an integer object constructed from a number or string x, or it returns 0.

Syntax:

int(string, base)

Parameters:

string : consists of 1's and 0's   ( or )  The string that contains a number, such as ‘9347' or ‘1734' and so on.
base : (integer value) base of the number.
10 is the default value of base.

Returns :

Returns an integer value in the given base that is the binary string's equivalent.

2)Converting given string in integer

Assume we have a string as a Str object that contains the value ‘28119′. We’ll pass the string to the int() function to convert it to an integer, or int object. Which returns the int object after converting this string to an integer.

Below is the implementation:

# given string value
string_value = '28119'
# converting given string to integer
integer = int(string_value)
# printing the integer value
print(integer)
# printing the type after converting string to integer
print('printing the type of object after converting string to integer', type(integer))

Output:

28119
printing the type of object after converting string to integer <class 'int'>

Explanation:

Because we didn't provide a base argument, the base value 10 was used by default when converting the string to an integer.

3)Converting Binary string to integer

Assume we have a Str object with the string ‘10101′. It contains a number’s binary representation. We’ll pass this string to the int() function along with the base value 2 to convert it to an integer, i.e., an int object. The int() function then converts the binary string to an integer and returns a value of int.

Below is the implementation:

# given binary string value
binary_String = '10101'
# converting given binarystring to integer
integer = int(binary_String, 2)
# printing the integer value
print(integer)

Output:

21

4)Converting Hexadecimal string to integer

Assume we have a Str object with the string ‘0x6DCF’. It contains a number’s hexadecimal representation. We’ll pass this string to the int() function along with the base value 16 to convert it to an integer, i.e., an int object. The int() function then converts the hex string to an integer and returns the object int.

Below is the implementation:

# given hexadecimal string value
hexadecimal_string = '0x6DCF'
# converting given hexadecimal to integer
integer = int(hexadecimal_string, 16)
# printing the integer value
print(integer)

Output:

28111

ValueError will be raised if the base value is not set to 16 with a hex string in the int() function. When converting a hexadecimal string to an int object, always remember to set the base value to 16.

5)Converting octal string to integer

Assume we have a Str object with the string ‘0o103650′. It contains a number’s octadecimal representation. We’ll pass this string to the int() function along with the base value 8 to convert it to an integer, i.e., an int object. The int() function then converts the octadecimal to an integer and returns the object int.

Below is the implementation:

# given octal string value
octal_string = '0o103650'
# converting given octal_string to integer
integer = int(octal_string, 8)
# printing the integer value
print(integer)

Output:

34728

6)Converting a number string with a comma to an integer

We can convert the number string with comma  to integer . By removing all the ‘,’ from the string by replacing the ‘,’ with empty character and then we can use int() to convert it to integer.

Below is the implementation:

# given string
given_string = '2803,11,02'
# replacing the , with empty charcater using replace() function
given_string = given_string.replace(',', "")
# converting the string to integer
intvalue = int(given_string)
# print the string
print(intvalue)

Output:

28031102

Related Programs:

Python: Convert String to Integer Read More »

Loop Iterate over all values of Dictionary

Loop / Iterate over all Values of Dictionary in Python

In Python, dictionaries are useful data structures that use keys for indexing. They are an unordered sequence of items (key-value pairs), so the order does not matter. The keys are not able to be changed. Dictionaries, like lists, can hold a variety of data types, including integers, floats, strings, NaN, Booleans, lists, arrays, and even nested dictionaries.

Given a dictionary, the task is to iterate over all values of the dictionary .

Examples:

Input:

dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}

Output:

600
300
900

Traverse the values of Dictionary

There are several ways to traverse the values of dictionary some of them are:

Method #1:Using for loop

To iterate over the keys of a dictionary, a dictionary object can also be used as an iterable object. We can easily iterate over all keys in the dictionary if we use it with a for loop. The value associated with that key can then be selected during iteration.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# using for loop to traverse the dictionary
for key in dictionary:
    print(dictionary[key])

Output:

600
300
900

Method #2:Using  items()

The dictionary class in Python has a function items() that returns an iterable sequence of all the dictionary’s key-value pairs, dict items. It shows all of the dictionary’s items (key-value pairs), so any changes to the original dictionary will be reflected in this sequence. We can’t use indexing with this sequence, either. This can be used in conjunction with a for loop to iterate over all pairs in the dictionary, and we can select the second element of the pair / tuple, i.e. the value, while iterating.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# using items()
for key, value in dictionary.items():
    # printing the value
    print(value)

Output:

600
300
900

Method #3:Using values()

The dictionary class in Python has a function values() that returns an iterable sequence of all dictionary values, i.e. dict values. It is a view of the dictionary’s entire value set, which means that any changes to the original dictionary will be reflected in this sequence. We can’t use indexing with this sequence, either. However, we can use this in conjunction with a for loop to iterate through all of the dictionary’s values.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# using values()
for value in dictionary.values():
    # printing the value
    print(value)

Output:

600
300
900

Method #4:Using  list Comprehension

This list comprehension can also be used to iterate through all of the dictionary’s values and print each one separately.

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# using list comprehension
print([value for value in dictionary.values()])

Output:

[600, 300, 900]

Method #5:Converting values to list

The sequence returned by the values() function can be passed to the list to create a list of all values in the dictionary .

We use list() function to achieve this. Print the list(values).

Below is the implementation:

# Given dictionary
dictionary = {'Hello': 600, 'world': 300, 'BTechGeeks': 900}
# converting given dictionary values to list using values() function
list_values = list(dictionary.values())
# print the dictionary values
for value in list_values:
    print(value)

Output:

600
300
900

Related Programs:

Loop / Iterate over all Values of Dictionary in Python Read More »

Python- How to unzip a file and Extract Single, multiple or all files from a ZIP archive

Python: How to unzip a file | Extract Single, multiple or all files from a ZIP archive | Syntax for ZipFile

In this tutorial, we will discuss different ways to unzip or extract single, multiple, or all files from the zip archive to a current or different directory. Also, you can learn what is a zip file and python unzip file along with the syntax. Moreover, let’s check the reasons to use the Zip Files in python. Click on the direct links available below and happily understand what you required regarding How to unzip files in Python?

What is Zip File?

A ZIP file is a single file containing one or more compressed files, it is an easy way to make large files smaller and keep related files together.

Why do we need zip files?

  • To lessen storage requirements.
  • To develop transfer speed over standard connections.

Python Unzip File

ZipFile class provides a member function to extract all the data from a ZIP archive. ZIP is the archive file format that supports lossless data compression.

In order to unzip a file in Python, make use of this ZipFile.extractall() method. The extractall() method takes a path, members, pwd as an argument, and extracts all the contents.

Also Check:

Syntax for ZipFile

ZipFile.extractall(path=None, members=None, pwd=None)

It accepts three arguments-

1. path: It shows the location where we want to extract our file

2. members:  It shows the list of files to be extracted

3. pwd: If the zip file is encrypted then pass the password in this argument default it will be None

Example of Python unzip

Let’s assume, in my current working directory, I have a zip file called Mail3.zip, and I wanted to unzip it with the help of the ZipFile.extractall() method. So, check out the following example program code:

# app.py

from zipfile import ZipFile

with ZipFile('Mail3.zip', 'r') as zipObj:
   # Extract all the contents of zip file in current directory
   zipObj.extractall()

Output:

python3 app.py

Lets’ first, import the zipfile module in our program,

from zipfile import ZipFile

Extract all files from a zip file to the current directory

So if want to zip file ‘program.zip’. in our current directory, let’s see how to extract all files from it.
To unzip it first create a ZipFile object by opening the zip file in read mode and then call extractall() on that object.

# app.py

from zipfile import ZipFile

with ZipFile('program.zip', 'r') as zipObj:
   # Extract all the contents of zip file in current directory
   zipObj.extractall()

In the output, it will extract the files in the same directory as your programming app.py file.

Extract all files from a zip file to Different Directory

To extract all the files from a zip file to another directory we can pass the destination location as an argument in extractall().

# app.py 
from zipfile import ZipFile
# Create a ZipFile Object and load program.zip in it
with ZipFile('program.zip', 'r') as zipObj:
   # Extract all the contents of zip file in different directory
   zipObj.extractall('temp')

It will extract all the files in ‘program.zip’ in the temp folder.

Extract few files from a large zip file based on condition

If we have a very large zip file and we need a few files from thousand of files in the archive. Unzipping all files from large zip can take minutes. But if we want only a few of the archived files, then instead of unzipping the whole file we can extract a few files too from the zip file.

For this, we are going to use the below syntax-

ZipFile.extract(member, path=None, pwd=None)

It accepts three arguments-

1. path: It shows the location where we want to extract our file

2. members:  Full name of the file to be extracted. It should one from the list of archived files names returned by ZipFile.namelist()

3. pwd: If the zip file is encrypted then pass the password in this argument default it will be None

# app.py 
from zipfile import ZipFile
# Create a ZipFile Object and load program.zip in it
with ZipFile('programDir.zip', 'r') as zipObj:
   # Get a list of all archived file names from the zip
   listOfFileNames = zipObj.namelist()
   # Iterate over the file names
   for fileName in listOfFileNames:
       # Check filename endswith csv
       if fileName.endswith('.csv'):
           # Extract a single file from zip
           zipObj.extract(fileName, 'temp_csv')

It will extract only csv files from the given zip archive.

Conclusion:

So in this article, you have seen how to unzip a file | Extract Single, multiple, or all files from a ZIP archive.

Thank you!

Python: How to unzip a file | Extract Single, multiple or all files from a ZIP archive | Syntax for ZipFile Read More »

Literals in Python

Literals in Python

Literals are a type of notation used in source code to represent a fixed value. They can also be defined as raw values or data that are given in variables or constants.

This article will teach you about the various types of literals in Python.

Python Literals

In Python, there are various types of literals. As an example,

1)Numeric Literals

In Python, numerical literals represent numbers and can be of the following types:

  • Integer Literal:
    • Both positive and negative numbers, including 0 are allowed. There must be no fractional parts.
    • Ex : 100 , -200 , 300 etc.
  • Float Literal:
    • These are real numbers with integer and fractional components.
    • Ex : 45.5 , 28.4 etc.
  • Binary Literal:
    • Numbers are represented in binary form.
    • For example, 1010 is binary literal for 10
  • Octal Literal:
    • Numbers are represented in octal form.
  • Hexadecimal Literal:
    • Numbers are represented in Hexadecimal form.
  • Complex Literal:
    • Complex numbers are represented by this type.
    • For example 6+ 3i ,4+2i etc.

2)Boolean Literals

In Python, only True and False are Boolean literals.

3)String literals

A string literal is made by enclosing a text(a set of characters) in single(”), double(“”), or triple(“”) quotes. We can write multi-line strings or show in the desired way by using triple quotes.

# string literals in python
# single quote representation of string
string1 = 'BTechGeeks'

# double quotes representation of string
string2 = "BTechGeeks"

# multiline representation of string
string3 = '''BTech
        Geeks
            Platform'''

print('single quote string:', string1)
print('double quote string:', string2)
print('multiline string :', string3)

Output:

single quote string: BTechGeeks
double quote string: BTechGeeks
multiline string : BTech
		Geeks
			Platform

4)Special literals

There is one special literal in Python (None). A null variable is described by the word ‘none.’ When ‘None’ is contrasted to something other than another ‘None,’ it returns false.

# special literal none
special = None
print(special)

Output:

None

5)Escape characters

  • \ :  Newline continuation
  • \\ : Display a single \
  • \’ : Display a single quote
  • \” : Display a double quote
  • \b : Backspace
  • \n : New Line
  • \t : Horizontal Tab
  • \v : Vertical Tab
  • \r : Enter

Related Programs:

Literals in Python Read More »

Pandas : How to merge Dataframes by index using Dataframe.merge()

How to merge Dataframes by index using Dataframe.merge() in Python ?

In this article we are going to see how we can merge two dataframes by using index of both the dataframes or by suing index of one dataframe and some columns of the other dataframe, and how we can keep a merged dataframe with similar indices. So, let’s start the exploring the topic.

DataFrame.merge()

SYNTAX :

DataFrame.merge(right, how='inner', on=None, left_on=None, right_on=None, index_left=False, index_right=False, sort=False, suffixes=('_x', '_y'), copy=True, indicator=False, validate=None)

For this short example, we will only focus on some arguments :

  • On : This is the column name on which the merge is supposed to be done.
  • Left_on : The column names of the left dataframe which are to be merged
  • Right_on : The column names of the right dataframe which are to be merged
  • index_left : It takes a boolean value whose default values is false. If it is true then it will choose indices from the left dataframe as join key.
  • index_right : It takes a boolean value whose default values is false. If it is true then it will choose indices from the right dataframe as join key.

To demonstrate we will be taking the following two dataframes :

Left dataframe :

     Regd     Name    Age        City         Exp
0    10        Jill          16.0     Tokyo          10
1    11        Rachel    38.0     Texas           5
2    12        Kirti        39.0     New York     7
3    13        Veena     40.0     Texas          21
4    14        Lucifer    NaN    Texas          30
5    15        Pablo      30.0    New York     7
6    16        Lionel     45.0    Colombia    11

Right dataframe :

     Regd     Exp       Wage     Bonus
0    10        Junior   75000      2000
1    11        Senior   72200     1000
2    12        Expert   90999     1100
3    13        Expert   90000     1000
4    14        Junior   20000      2000
5    15        Junior   50000      1500
6    16        Senior   81000     1000

Merging two Dataframes by index of both the dataframes :

Here you might have noticed we have a common column named ‘Regd’ . So we can merge both the dataframes by passing left_index and right_index as true in the function.

# Program :


# Importing the module
import pandas as pd
import numpy as np

#Left Dataframe
students = [(10,'Jill',    16,     'Tokyo',    10),
            (11,'Rachel',  38,     'Texas',     5),
            (12,'Kirti',   39,     'New York',  7),
            (13,'Veena',   40,     'Texas',    21),
            (14,'Lucifer', np.NaN, 'Texas',    30),
            (15,'Pablo',   30,     'New York',  7),
            (16,'Lionel',  45,     'Colombia', 11) ]
lDfObj = pd.DataFrame(students, columns=['Regd','Name','Age','City','Exp'],index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

#Right dataframe
wage = [(10, 'Junior', 75000, 2000) ,
        (11, 'Senior', 72200, 1000) ,
        (12, 'Expert', 90999, 1100) ,
        (13, 'Expert', 90000, 1000) ,
        (14, 'Junior', 20000, 2000) ,
        (15, 'Junior', 50000, 1500) ,
        (16, 'Senior', 81000, 1000)]
rDfObj = pd.DataFrame(wage, columns=['Regd','Exp','Wage','Bonus'] , index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

#Merging both the dataframes
newDF = lDfObj.merge(rDfObj, left_index=True, right_index=True)

#printing the merged dataframe
print("The merged dataframe is-")
print(newDF)

Output :
The merged dataframe is-
     Regd_x    Name     Age       City         Exp_x   Regd_y    Exp_y      Wage     Bonus
a      10         Jill         16.0      Tokyo         10        10          Junior     75000      2000
b      11        Rachel   38.0      Texas           5         11          Senior     72200      1000
c      12         Kirti       39.0      New York    7         12           Expert    90999     1100
d      13        Veena    40.0      Texas           21       13          Expert     90000      1000
e      14        Lucifer    NaN     Texas           30       14          Junior     20000      2000
f      15         Pablo      30.0      New York    7         15          Junior     50000      1500
g      16       Lionel      45.0      Colombia    11       16          Senior     81000      1000

Finally, if we want to merge a dataframe by the index of the first dataframe with some column from the other dataframe, we can also do that.

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Read more Articles on Python Data Analysis Using Padas

Pandas : How to merge Dataframes by index using Dataframe.merge() Read More »

Select Rows & Columns by Name or Index in DataFrame using loc & iloc | Python Pandas

How to select rows and columns by Name or Index in DataFrame using loc and iloc in Python ?

We will discuss several methods to select rows and columns in a dataframe. To select rows or columns we can use loc( ), iloc( ) or using the [ ] operator.

To demonstrate the various methods we will be using the following dataset :

      Name      Score        City
0     Jill           16.0       Tokyo
1     Rachel     38.0      Texas
2     Kirti         39.0       New York
3     Veena      40.0      Texas
4     Lucifer     NaN      Texas
5     Pablo       30.0       New York
6     Lionel      45.0       Colombia

Method-1 : DataFrame.loc | Select Column & Rows by Name

We can use the loc( ) function to select rows and columns.

Syntax :

dataFrame.loc[<ROWS RANGE> , <COLUMNS RANGE>]

We have to enter the range of rows or columns, and it will select the specified range.

If we don’t give a value and pass ‘:’ instead, it will select all the rows or columns.

Select a Column by Name in DataFrame using loc[ ] :

As we need to select a single column only, we have to pass ‘:’ in row range place.

So, let’s see the implementation of it.

#Program :

import pandas as pd
import numpy as np
#data
students = [
('Jill',    16,     'Tokyo',),
('Rachel',  38,     'Texas',),
('Kirti',   39,     'New York'),
('Veena',   40,     'Texas',),
('Lucifer', np.NaN, 'Texas'),
('Pablo',   30,     'New York'),
('Lionel',  45,     'Colombia',)]
#Creating the dataframe object
dfObj = pd.DataFrame(students, columns=['Name','Score','City'])
#Selecting the 'Score solumn'
columnD = dfObj.loc[:,'Score']
print(columnD)
Output :
0    16.0
1    38.0
2    39.0
3    40.0
4     NaN
5    30.0
6    45.0
Name: Score, dtype: float64

Select multiple Columns by Name in DataFrame using loc[ ] :

To select multiple columns, we have to pass the column names as a list into the function.

So, let’s see the implementation of it.

#Program

import pandas as pd
import numpy as np
#data
students = [('Jill',    16,     'Tokyo',),
('Rachel',  38,     'Texas',),
('Kirti',   39,     'New York'),
('Veena',   40,     'Texas',),
('Lucifer', np.NaN, 'Texas'),
('Pablo',   30,     'New York'),
('Lionel',  45,     'Colombia',)]
#Creating the dataframe object
dfObj = pd.DataFrame(students, columns=['Name','Score','City'], index=['a','b','c','d','e','f','g'])
#Selecting multiple columns i.e 'Name' and 'Score' column
columnD = dfObj.loc[:,['Name','Score']]
print(columnD)
Output :
     Name      Score
a     Jill          16.0
b   Rachel     38.0
c    Kirti         39.0
d    Veena     40.0
e  Lucifer      NaN
f    Pablo       30.0
g   Lionel       45.0

Select a single row by Index Label in DataFrame using loc[ ] :

Just like the column, we can also select a single row by passing its name and in place of column range passing ‘:’.

So, let’s see the implementation of it.

#Program :

import pandas as pd
import numpy as np
#data
students = [('Jill',    16,     'Tokyo',),
('Rachel',  38,     'Texas',),
('Kirti',   39,     'New York'),
('Veena',   40,     'Texas',),
('Lucifer', np.NaN, 'Texas'),
('Pablo',   30,     'New York'),
('Lionel',  45,     'Colombia',)]
#Creating the dataframe object
dfObj = pd.DataFrame(students, columns=['Name','Score','City'], index=['a','b','c','d','e','f','g'])
#Selecting a single row i.e 'b' row
selectData = dfObj.loc['b',:]
print(selectData)

Output :
Name       Rachel
Score        38.0
City          Texas
Name: b, dtype: object

Select multiple rows by Index labels in DataFrame using loc[ ] :

To select multiple rows we have to pass the names as a list into the function.

So, let’s see the implementation of it.

#Program :

import pandas as pd
import numpy as np
#data
students = [('Jill',    16,     'Tokyo',),
('Rachel',  38,     'Texas',),
('Kirti',   39,     'New York'),
('Veena',   40,     'Texas',),
('Lucifer', np.NaN, 'Texas'),
('Pablo',   30,     'New York'),
('Lionel',  45,     'Colombia',)]
#Creating the dataframe object
dfObj = pd.DataFrame(students, columns=['Name','Score','City'], index=['a','b','c','d','e','f','g'])
#Selecting multiple rows i.e 'd' and 'g'
selectData = dfObj.loc[['d','g'],:]
print(selectData)

Output :
      Name   Score      City
d    Veena   40.0       Texas
g    Lionel   45.0       Colombia

Select multiple row & columns by Labels in DataFrame using loc[ ] :

To select multiple rows and columns we have to pass the list of rows and columns we want to select into the function.

So, let’s see the implementation of it.

#Program :

import pandas as pd
import numpy as np
#data
students = [('Jill',    16,     'Tokyo',),
('Rachel',  38,     'Texas',),
('Kirti',   39,     'New York'),
('Veena',   40,     'Texas',),
('Lucifer', np.NaN, 'Texas'),
('Pablo',   30,     'New York'),
('Lionel',  45,     'Colombia',)]
#Creating the dataframe object
dfObj = pd.DataFrame(students, columns=['Name','Score','City'], index=['a','b','c','d','e','f','g'])
#Selecting multiple rows and columns i.e 'd' and 'g' rows and 'Name' , 'City' column
selectData = dfObj.loc[['d','g'],['Name','City']]
print(selectData)

Output :
      Name      City
d   Veena      Texas
g  Lionel       Colombia

Method-2 : DataFrame.iloc | Select Column Indexes & Rows Index Positions

We can use the iloc( ) function to select rows and columns. It is quite similar to loc( ) function .

Syntax-

dataFrame.iloc

[<ROWS INDEX RANGE> , <COLUMNS INDEX RANGE>]

The function selects rows and columns in the dataframe by the index position we pass into the program. And just as like loc( ) if ‘:’ is passed into the function, all the rows/columns are selected.

Select a single column by Index position :

We have to pass the index of the column with ‘:’ in place of the row index.

So, let’s see the implementation of it.

#Program :

import pandas as pd
import numpy as np
#data
students = [
('Jill',    16,     'Tokyo',),
('Rachel',  38,     'Texas',),
('Kirti',   39,     'New York'),
('Veena',   40,     'Texas',),
('Lucifer', np.NaN, 'Texas'),
('Pablo',   30,     'New York'),
('Lionel',  45,     'Colombia',)]
#Creating the dataframe object
dfObj = pd.DataFrame(students, columns=['Name','Score','City'], index=['a','b','c','d','e','f','g'])
#Selecting a single column at the index 2
selectData = dfObj.iloc[:,2]
print(selectData)
Output :
a       Tokyo
b       Texas
c        New York
d       Texas
e       Texas
f        New York
g       Colombia
Name: City, dtype: object

Select multiple columns by Indices in a list :

To select multiple columns by indices we just pass the indices as series into the column value.

So, let’s see the implementation of it.

#Program :

import pandas as pd
import numpy as np
#data
students = [
('Jill',    16,     'Tokyo',),
('Rachel',  38,     'Texas',),
('Kirti',   39,     'New York'),
('Veena',   40,     'Texas',),
('Lucifer', np.NaN, 'Texas'),
('Pablo',   30,     'New York'),
('Lionel',  45,     'Colombia',)]
#Creating the dataframe object
dfObj = pd.DataFrame(students, columns=['Name','Score','City'], index=['a','b','c','d','e','f','g'])
#Selecting multiple columns at the index 0 & 2
selectData = dfObj.iloc[:,[0,2]]
print(selectData)
Output :
        Name       City
a      Jill            Tokyo
b      Rachel     Texas
c      Kirti          New York
d      Veena      Texas
e      Lucifer     Texas
f      Pablo        New York
g     Lionel       Colombia

Select multiple columns by Index range :

To select multiple columns by index range we just pass the indices as series into the column value.

So, let’s see the implementation of it.

#Program :

import pandas as pd
import numpy as np
#data
students = [
('Jill',    16,     'Tokyo',),
('Rachel',  38,     'Texas',),
('Kirti',   39,     'New York'),
('Veena',   40,     'Texas',),
('Lucifer', np.NaN, 'Texas'),
('Pablo',   30,     'New York'),
('Lionel',  45,     'Colombia',)]
#Creating the dataframe object
dfObj = pd.DataFrame(students, columns=['Name','Score','City'], index=['a','b','c','d','e','f','g'])
#Selecting multiple columns from the index 1 to 3
selectData = dfObj.iloc[:,1:3]
print(selectData)
Output :
      Score      City
a    16.0         Tokyo
b    38.0         Texas
c    39.0         New York
d    40.0         Texas
e    NaN        Texas
f     30.0         New York
g    45.0         Colombia

Select single row by Index Position :

Just like columns we can pass the index and select the row.

So, let’s see the implementation of it.

#Program :

import pandas as pd
import numpy as np
#data
students = [
('Jill',    16,     'Tokyo',),
('Rachel',  38,     'Texas',),
('Kirti',   39,     'New York'),
('Veena',   40,     'Texas',),
('Lucifer', np.NaN, 'Texas'),
('Pablo',   30,     'New York'),
('Lionel',  45,     'Colombia',)]
#Creating the dataframe object
dfObj = pd.DataFrame(students, columns=['Name','Score','City'], index=['a','b','c','d','e','f','g'])
#Selecting a single row with index 2
selectData = dfObj.iloc[2,:]
print(selectData)
Output :
Name        Kirti
Score        39.0
City     New York
Name: c, dtype: object

Select multiple rows by Index positions in a list :

To do this we can pass the indices of positions to select into the function.

So, let’s see the implementation of it.

#Program :

import pandas as pd
import numpy as np
#data
students = [
('Jill',    16,     'Tokyo',),
('Rachel',  38,     'Texas',),
('Kirti',   39,     'New York'),
('Veena',   40,     'Texas',),
('Lucifer', np.NaN, 'Texas'),
('Pablo',   30,     'New York'),
('Lionel',  45,     'Colombia',)]
#Creating the dataframe object
dfObj = pd.DataFrame(students, columns=['Name','Score','City'], index=['a','b','c','d','e','f','g'])
#Selecting multiple rows by passing alist i.e. 2 & 5
selectData = dfObj.iloc[[2,5],:]
print(selectData)
 Output :
     Name    Score      City
c   Kirti      39.0       New York
f    Pablo   30.0       New York

Select multiple rows by Index range :

To select a range of rows we pass the range separated by a ‘:’ into the function.

So, let’s see the implementation of it.

#Program :

import pandas as pd
import numpy as np
#data
students = [
('Jill',    16,     'Tokyo',),
('Rachel',  38,     'Texas',),
('Kirti',   39,     'New York'),
('Veena',   40,     'Texas',),
('Lucifer', np.NaN, 'Texas'),
('Pablo',   30,     'New York'),
('Lionel',  45,     'Colombia',)]
#Creating the dataframe object
dfObj = pd.DataFrame(students, columns=['Name','Score','City'], index=['a','b','c','d','e','f','g'])
#Selecting multiple rows by range i.e. 2 to 5
selectData = dfObj.iloc[2:5,:]
print(selectData)
Output :
      Name      Score      City
c     Kirti        39.0        New York
d     Veena     40.0       Texas
e     Lucifer    NaN       Texas

Select multiple rows & columns by Index positions :

To select multiple rows and columns at once, we pass the indices directly into function.

So, let’s see the implementation of it.

#Program :

import pandas as pd
import numpy as np
#data
students = [
('Jill',    16,     'Tokyo',),
('Rachel',  38,     'Texas',),
('Kirti',   39,     'New York'),
('Veena',   40,     'Texas',),
('Lucifer', np.NaN, 'Texas'),
('Pablo',   30,     'New York'),
('Lionel',  45,     'Colombia',)]
#Creating the dataframe object
dfObj = pd.DataFrame(students, columns=['Name','Score','City'], index=['a','b','c','d','e','f','g'])
#Selecting multiple rows and columns
selectData = dfObj.iloc[[1,2],[1,2]]
print(selectData)
Output :
    Score      City
b   38.0      Texas
c   39.0       New York

Method-3 : Selecting Columns in DataFrame using [ ] operator

The [ ] operator selects the data according to the name provided to it. However, when a non-existent label is passed into it, it sends a KeyError.

Select a Column by Name :

So, let’s see the implementation of it.

#Program :

import pandas as pd
import numpy as np
#data
students = [
('Jill',    16,     'Tokyo',),
('Rachel',  38,     'Texas',),
('Kirti',   39,     'New York'),
('Veena',   40,     'Texas',),
('Lucifer', np.NaN, 'Texas'),
('Pablo',   30,     'New York'),
('Lionel',  45,     'Colombia',)]
#Creating the dataframe object
dfObj = pd.DataFrame(students, columns=['Name','Score','City'], index=['a','b','c','d','e','f','g'])
#Select a single column name using [ ]
selectData = dfObj['Name']
print(selectData)
Output :
a       Jill
b     Rachel
c      Kirti
d      Veena
e    Lucifer
f      Pablo
g     Lionel
Name: Name, dtype: object

Select multiple columns by Name :

To select multiple columns we just pass a list of their names into [ ].

So, let’s see the implementation of it.

#Program :

import pandas as pd
import numpy as np
#data
students = [
('Jill',    16,     'Tokyo',),
('Rachel',  38,     'Texas',),
('Kirti',   39,     'New York'),
('Veena',   40,     'Texas',),
('Lucifer', np.NaN, 'Texas'),
('Pablo',   30,     'New York'),
('Lionel',  45,     'Colombia',)]
#Creating the dataframe object
dfObj = pd.DataFrame(students, columns=['Name','Score','City'], index=['a','b','c','d','e','f','g'])
#Select multiple columns using [ ]
selectData = dfObj[['Name','City']]
print(selectData)
Output :
       Name        City
a      Jill            Tokyo
b      Rachel     Texas
c      Kirti          New York
d      Veena       Texas
e      Lucifer      Texas
f       Pablo        New York
g      Lionel       Colombia

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Read more Articles on Python Data Analysis Using Padas – Select items from a Dataframe

Select Rows & Columns by Name or Index in DataFrame using loc & iloc | Python Pandas Read More »

Pandas: Create Series from list in python

How to create series from list in Python ?

In this article we will get to know about how we will convert list to a series using Pandas.

Series class provides a constructor in python.

Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)

Where,

  • data : It is array-like and iterable sequence. It adds the elements in this iterable as values in the Series.
  • index : It is array-like and iterable sequence. It adds the elements in this iterable as indexes in the Series.
  • dtype : It represents the data type of the output series.

Now, we will create series class constructor to create a Pandas Series object from a list. So, let’s start exploring the topic.

Creating Pandas Series from a list :

Let’s take an example where we will convert a list into Pandas series object by passing the list in Series class constructor.

Let’s see how it is actually implemented.

#Program :


import pandas as sc

# List for strings
list_words = ['alexa', 'siri', 'try', 'sometime', 'why', 'it']

# To create a series object from string list
series_objs = sc.Series(list_words)

print('New series object: ')
print(series_objs)
Output:
New Series Objetct:
0      alexa
1      siri
2    try
3     sometime
4     why
5     it
dtype: object

Creating Pandas Series from two lists :

Let’s take a scenario where we want to have only some specific indices in Series object, so in that case we would pass another list of same size to Series class constructor as the index argument.

Let’s see how it is actually implemented.

#Program :


import pandas as sc

# List for values
list_words = ['alexa', 'siri', 'please', 'try', 'sometime', 'it']

# List for index
index_tags = ['i', 'ii', 'iii', 'iv', 'v', 'vi']

# To create a series from two list i.e. one for value, one for index
series_objs = sc.Series(list_words, index=index_tags)

print('New series object: ')
print(series_objs)
Output:
New Series Object:
i      alexa
ii      siri
iii    please
iv    try
v    sometime
vi    it
dtype: object

By default the index values start from 0 to N-1 (N= No. of elements in Series object).

Creating Pandas Series object from a list but with dissimilar datatype :

Let we want to form a Series object from a list of integer, but the items should be stored as strings inside Series object i.e. here we would convert list into Pandas Series object by converting integers into string. To get the output we should pass dtype argument in Series Constructor.

Let’s see how it is actually implemented.

#Program :


import pandas as sc

# List for integers
list_nums = [101, 100, 153, 36, 58]

# To create a series with list of different type i.e. str
series_objs = sc.Series(list_nums, index= ['i', 'ii', 'iii', 'iv', 'v'],dtype=str)

print('New Series Object:')
print(series_objs)
Output:
i     101
ii    100
iii   153
iv    36
v    58
dtype: object

Converting a heterogeneous list to Pandas Series object :

Let’s take a example of heterogenous list where if we don’t provide any dtype argument in Series constructor, then all the items will be converted to str type.

Let’s see how it is actually implemented.

#Program :


import pandas as sc

# List for mixed datatypes
list_mixed = ['some',99,'will','be',10.57,'yes']

series_objs = sc.Series(list_mixed,index= ['i', 'ii', 'iii', 'iv', 'v'])

print(series_objs)
Output:
i    some
ii    99
iii   will
iv   be
v    10.57
vi    yes
dtype: object

Converting a booli list (Bool type) to Pandas Series object :

Let’s take an example where we would create Series object from booli list of boolean type.

Let’s see how it is actually implemented.

#Program :

import pandas as sc

booli_list = [False, True, False, False, True]

# Convert a booli list to Series object of bool data type.
series_objs = sc.Series(booli_list,index=['i', 'ii', 'iii', 'iv', 'v'])

print('New Series Object:')
print(series_objs)
Output:
Contents of the Series Object:
a     False
b    True
c    False
d    False
e     True
dtype: bool

Pandas: Create Series from list in python Read More »

Convert NumPy array to list in python

How to convert NumPy array to list in python ?

In this article we are going to discuss about how we can convert a 1D or 2D or 3D Numpy Array to a list or list of lists.

Converting Numpy Array to List :

In Python, ndarray class of Numpy Module provides tolist() function which can be used to convert a 1D array to list. All the elements of the 1D array will be contained as the items of the list.

So, let’s see how it actually works.

# Program :

import numpy as np
# NumPy array created
arr = np.array([1, 2, 3, 4, 5])
# Printing the NumPy array
print('Numpy Array:', arr)

# Converting 1D Numpy Array to list
num_list = arr.tolist()

# Printing the list
print('List: ', num_list)
Outptut :
Numpy Array: [1 2 3 4 5] 
List: [1, 2, 3, 4, 5]

Converting 2D Numpy array to list of lists :

We can use the same tolist() function to convert the 2D Numpy array to list of lists i.e called as Nested List.

So, let’s see how it actually works.

# Program :

import numpy as np
# 2D Numpy Array created
arr = np.array([[11, 12, 13, 14],
                [15, 16, 17, 18],
                [19, 20, 21, 22]])
# Printing 2D numpy array                
print('2D Numpy Array:')
print(arr)

# Converting Numpy Array to list of lists
list_of_lists = arr.tolist()

#Printing the nested list
print('List of lists:')
print(list_of_lists)
Output :
2D Numpy Array:
[[11, 12, 13, 14], 
[15, 16, 17, 18], 
[19, 20, 21, 22]]
List of lists:

Converting 2D Numpy Array to a flattened list :

We can also convert the 2D NumPy array to a flat list. For that first we have to convert the 2D NumPy array to 1D array by using flatten() function. Then convert 1D array to list by using tolist() function.

So, let’s see how it actually works.

# Program :

import numpy as np
# 2D Numpy Array created
arr = np.array([[1, 2, 3, 4],
                [5, 6, 7, 8],
                [3, 3, 3, 3]])
# Printing 2D Numpy array                
print('2D Numpy Array:')
print(arr)

# Converting 2D Numpy array toa single list
num_list = arr.flatten().tolist()

#Printing list
print('List:', num_list)
Output :
2D Numpy Array:
[[1, 2, 3, 4], 
[5, 6, 7, 8], 
[3, 3, 3, 3]]
2D Numpy Array:
[1, 2, 3, 4, 5, 6, 7, 8, 3, 3, 3, 3]

Convert 3D Numpy array to nested list :

Similarly the 3D Numpy array can also be converted by using tolist() function into list of nested lists.

So, let’s see how it actually works.

# Program :

import numpy as np

# 3D Numpy Array created
arr = np.ones( (2,4,5) , dtype=np.int64)

#Prinitng 3D Numpy array 
print('3D Numpy Array:')
print(arr)

# Converting 3D Numpy Array to nested list
nested_list = arr.tolist()

# Printing nested list
print('Nested list:')
print(nested_list)
Output :
3D Numpy Array:
[[[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]]


[[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]]]
Nested list:
[[[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]],
[[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1], 
[1, 1, 1, 1, 1]]]

Converting 3D Numpy Array to a flat list :

The process is same like how we converted the 2D Numpy array to flatten list. Similarly, use the flatten() function to convert the 3D Numpy array to 1D array. Then convert the 1D Numpy array to flat list by using tolist() function.

So, let’s see how it actually works.

# Program :

import numpy as np
# 3D Numpy Array created
arr = np.ones( (2,4,5) , dtype=np.int64)
# Printing 3D Numpy array
print('3D Numpy Array:')
print(arr)

# Converting 3D Numpy Array to flat list
flat_list = arr.flatten().tolist()

# Printing the list
print('Flat list:')
print(flat_list)
Output :
3D Numpy Array:
[[[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]]
[[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]]]
Flat list:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

 

Convert NumPy array to list in python Read More »