Python

Pandas- Loop or Iterate over all or certain columns of a dataframe

Pandas : Loop or Iterate over all or certain columns of a dataframe

In this article, we will discuss how to loop or Iterate overall or certain columns of a DataFrame. Also, you may learn and understand what is dataframe and how pandas dataframe iterate over columns with the help of great explanations and example codes.

About DataFrame

A Pandas DataFrame is a 2-dimensional data structure, like a 2-dimensional array, or a table with rows and columns.

First, we are going to create a dataframe that will use in our article.

import pandas as pd

employees = [('Abhishek', 34, 'Sydney') ,
           ('Sumit', 31, 'Delhi') ,
           ('Sampad', 16, 'New York') ,
           ('Shikha', 32,'Delhi') ,
            ]

#load data into a DataFrame object:
df = pd.DataFrame(employees, columns=['Name', 'Age', 'City'], index=['a', 'b', 'c', 'd'])

print(df)

Output:

    Name       Age    City
a  Abhishek  34    Sydney
b  Sumit       31    Delhi
c  Sampad   16     New York
d  Shikha     32     Delhi

Also Check:

Using DataFrame.iteritems()

We are going to iterate columns of a dataframe using DataFrame.iteritems().

Dataframe class provides a member function iteritems().

import pandas as pd
employees = [('Abhishek', 34, 'Sydney') ,
             ('Sumit', 31, 'Delhi') ,
             ('Sampad', 16, 'New York') ,
             ('Shikha', 32,'Delhi') , ]
#load data into a DataFrame object:
df = pd.DataFrame(employees, columns=['Name', 'Age', 'City'], index=['a', 'b', 'c', 'd'])
# Yields a tuple of column name and series for each column in the dataframe
for (columnName, columnData) in df.iteritems():
   print('Colunm Name : ', columnName)
   print('Column Contents : ', columnData.values)

Output:

Colunm Name : Name
Column Contents : ['Abhishek' 'Sumit' 'Sampad' 'Shikha']
Colunm Name : Age
Column Contents : [34 31 16 32]
Colunm Name : City
Column Contents : ['Sydney' 'Delhi' 'New York' 'Delhi']

In the above example, we have to return an iterator that can be used to iterate over all the columns. For each column, it returns a tuple containing the column name and column contents.

Iterate over columns in dataframe using Column Names

import pandas as pd
employees = [('Abhishek', 34, 'Sydney') ,
             ('Sumit', 31, 'Delhi') ,
             ('Sampad', 16, 'New York') ,
             ('Shikha', 32,'Delhi') , ]
#load data into a DataFrame object:
df = pd.DataFrame(employees, columns=['Name', 'Age', 'City'], index=['a', 'b', 'c', 'd'])
# Yields a tuple of column name and series for each column in the dataframe
for column in df:
   # Select column contents by column name using [] operator
   columnSeriesObj = df[column]
   print('Colunm Name : ', column)
   print('Column Contents : ', columnSeriesObj.values)

Output:

Colunm Name : Name
Column Contents : ['Abhishek' 'Sumit' 'Sampad' 'Shikha']
Colunm Name : Age
Column Contents : [34 31 16 32]
Colunm Name : City
Column Contents : ['Sydney' 'Delhi' 'New York' 'Delhi']

ln the above example, we can see that Dataframe.columns returns a sequence of column names on which we put iteration and return column name and content.

Iterate Over columns in dataframe in reverse order

import pandas as pd
employees = [('Abhishek', 34, 'Sydney') ,
             ('Sumit', 31, 'Delhi') ,
             ('Sampad', 16, 'New York') ,
             ('Shikha', 32,'Delhi') , ]
#load data into a DataFrame object:
df = pd.DataFrame(employees, columns=['Name', 'Age', 'City'], index=['a', 'b', 'c', 'd'])
# Yields a tuple of column name and series for each column in the dataframe
for column in reversed(df.columns):
   # Select column contents by column name using [] operator
   columnSeriesObj = df[column]
   print('Colunm Name : ', column)
   print('Column Contents : ', columnSeriesObj.values)

Output:

Colunm Name : City
Column Contents : ['Sydney' 'Delhi' 'New York' 'Delhi']
Colunm Name : Age
Column Contents : [34 31 16 32]
Colunm Name : Name
Column Contents : ['Abhishek' 'Sumit' 'Sampad' 'Shikha']

We have used reversed(df.columns)which given us the reverse column name and its content.

Iterate Over columns in dataframe by index using iloc[]

import pandas as pd
employees = [('Abhishek', 34, 'Sydney') ,
             ('Sumit', 31, 'Delhi') ,
             ('Sampad', 16, 'New York') ,
             ('Shikha', 32,'Delhi') , ]
#load data into a DataFrame object:
df = pd.DataFrame(employees, columns=['Name', 'Age', 'City'], index=['a', 'b', 'c', 'd'])
# Yields a tuple of column name and series for each column in the dataframe
for index in range(df.shape[1]):
   print('Column Number : ', index)
   # Select column by index position using iloc[]
   columnSeriesObj = df.iloc[: , index]
   print('Column Contents : ', columnSeriesObj.values)

Output:

Column Number : 0
Column Contents : ['Abhishek' 'Sumit' 'Sampad' 'Shikha']
Column Number : 1
Column Contents : [34 31 16 32]
Column Number : 2
Column Contents : ['Sydney' 'Delhi' 'New York' 'Delhi']

So in the above example, you can see that we have iterate over all columns of the dataframe from the 0th index to the last index column. We have selected the contents of the columns using iloc[].

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

Conclusion:

At last, I can say that the above-explained different methods to iterate over all or certain columns of a dataframe. aids you a lot in understanding the Pandas: Loop or Iterate over all or certain columns of a dataframe. Thank you!

Pandas : Loop or Iterate over all or certain columns of a dataframe Read More »

What is a Dictionary in Python and why do we need it

What is a Dictionary in Python and why do we need it

Dictionaries are Python’s implementation of an associative list, which may be a arrangement . A dictionary may be a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

Dictionary in Python and why do we need it

1)Dictionary in Python

This is a dictionary example that contains cricket names as keys and the highest score as values. Elements are stored as key-value pairs in the dictionary, where each value is mapped to one key. It is also called a hash table or an associative array.

dictionary

There are four elements in the above dictionary, i.e. four key-value pairs.

  1. Devilliers & 176
  2. Virat Kohli & 183
  3. Dhoni & 183
  4. Gayle & 237

2)Use of Dictionary

As a dictionary, it holds the elements in key-value mapping format and uses hashing internally; as a result, we can easily retrieve a value from the dictionary by its key. In the best-case scenario, its complexity is O(1), while in the worst-case scenario, it can be O(n).

3)Creating a new Dictionary

We can create dictionary by two ways i.e two types of syntaxes.

  1. dict()
  2. {}

It will generate an empty dictionary.
Transfer the key-value pairs in curly braces to build a dictionary of objects. A colon will also be used to divide the key and value in each pair (:).

Let us create a sample dictionary and print the key value pairs in it

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# printing the dictionary
print(dictionary)

Output:

{'This': 100, 'is': 200, 'BTechGeeks': 300}

4)The most important things to know about keys in the dictionary

Keys in the dictionary are always unique, and they must be of an immutable data type, such as strings, numbers, or tuples.
This means that once a key-value pair is added to the dictionary, we cannot change the key itself, but we can change the value associated with it.

For example, suppose we make a dictionary with duplicate keys and print its contents.

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'This': 300}
# printing the dictionary
print(dictionary)

Output:

{'This': 300, 'is': 200}

5)The most important things to know about values in the dictionary

A dictionary’s values can be of any type.

Let’s make a dictionary where the key is an integer and the value is a list of strings.

Below is the implementation:

# given dictionary
dictionary = {1: ["HELLO", "THIS", 453], 
              2: ["BTECHGEEKS", 345, 87, 4.5], 
              3: ["PYTHON", True, 3.2, 100]}
# printing the dictionary
print(dictionary)

Output:

{1: ['HELLO', 'THIS', 453], 2: ['BTECHGEEKS', 345, 87, 4.5], 3: ['PYTHON', True, 3.2, 100]}

6)Accessing an element in dictionary

Using the [] operator on the dictionary object, we can access a specific item/pair in a dictionary. If we use the dictionary object’s operator [] and pass a key, it will return its value as shown below.

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'This': 300}
# printing the element value in dictionary
print(dictionary['is'])

Output:

200

Now when we pass a key which does not exist in the dictionary, a KeyError is returned

Below is the implementation:

# given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# printing the element value in dictionary
print(dictionary['python'])

Output:

Traceback (most recent call last):
  File "/home/eb2788937138651d15b1bf1915ff16a5.py", line 4, in <module>
    print(dictionary['python'])
KeyError: 'python'

Related Programs:

What is a Dictionary in Python and why do we need it Read More »

Sorting 2D Numpy Array by column or row in Python

Sorting 2D Numpy Array by column or row in Python | How to sort the NumPy array by column or row in Python?

In this tutorial, we are going to discuss how to sort the NumPy array by column or row in Python. Just click on the direct links available here and directly jump into the example codes on sorting 2D Numpy Array by Column or Row in Python.

How to Sort the NumPy Array by Column in Python?

In this section, you will be learning the concept of Sorting 2D Numpy Array by a column

Firstly, we have to import a numpy module ie.,

import numpy as np

After that, create a 2D Numpy array i.e.,

# Create a 2D Numpy array list of list
arr2D = np.array([[21, 22, 23, 20], [21, 17, 13, 14], [13, 10, 33, 19]])
print('2D Numpy Array')
print(arr2D)

Output:

2D Numpy Array
[[21 22 23 20]
[21 17 13 14]
[13 10 33 19]]

Suppose if we want to sort this 2D array by 2nd column like this,

[[21 7 23 14]
[31 10 33 7]
[11 12 13 22]]

To do that, first, we have to change the positioning of all rows in the 2D numpy array on the basis of sorted values of the 2nd column i.e. column at index 1.

Do Check:

Let’s see how to sort it,

Sorting 2D Numpy Array by column at index 1

In this, we will use arr2D[:,columnIndex].argsort()which will give the array of indices that sort this column.

import numpy as np

# Create a 2D Numpy array list of list
arr2D = np.array([[21, 22, 23, 20], [21, 17, 13, 14], [13, 10, 33, 19]])
print('2D Numpy Array')
print(arr2D)
columnIndex = 1
# Sort 2D numpy array by 2nd Column
sortedArr = arr2D[arr2D[:,columnIndex].argsort()]
print('Sorted 2D Numpy Array')
print(sortedArr)

Output:

2D Numpy Array
[[21 22 23 20]
[21 17 13 14]
[13 10 33 19]]

Sorted 2D Numpy Array
[[13 10 33 19]
[21 17 13 14]
[21 22 23 20]]

So in the above example, you have seen we changed the position of all rows in an array on sorted values of the 2nd column means column at index 1.

Sorting 2D Numpy Array by column at index 0

Let’s see how it will work when we give index 0.

import numpy as np

# Create a 2D Numpy array list of list
arr2D = np.array([[21, 22, 23, 20], [21, 17, 13, 14], [13, 10, 33, 19]])
print('2D Numpy Array')
print(arr2D)
# Sort 2D numpy array by first column
sortedArr = arr2D[arr2D[:,0].argsort()]
print('Sorted 2D Numpy Array')
print(sortedArr)

Output:

2D Numpy Array
[[21 22 23 20]
[21 17 13 14]
[13 10 33 19]]

Sorted 2D Numpy Array
[[13 10 33 19]
[21 22 23 20]
[21 17 13 14]]

Sorting 2D Numpy Array by the Last Column

import numpy as np

# Create a 2D Numpy array list of list
arr2D = np.array([[21, 22, 23, 20], [21, 17, 13, 14], [13, 10, 33, 19]])
print('2D Numpy Array')
print(arr2D)
# Sort 2D numpy array by last column
sortedArr = arr2D[arr2D[:, -1].argsort()]
print('Sorted 2D Numpy Array')
print(sortedArr)

Output:

2D Numpy Array
[[21 22 23 20]
[21 17 13 14]
[13 10 33 19]]

Sorted 2D Numpy Array
[[21 17 13 14]
[13 10 33 19]
[21 22 23 20]]

How to Sort the NumPy array by Row in Python?

By using similar logic, we can also sort a 2D Numpy array by a single row i.e. mix-up the columns of the 2D numpy array to get the furnished row sorted.

Look at the below examples and learn how it works easily,

Let’s assume, we have a 2D Numpy array i.e.

# Create a 2D Numpy array list of list
arr2D = np.array([[11, 12, 13, 22], [21, 7, 23, 14], [31, 10, 33, 7]])
print('2D Numpy Array')
print(arr2D)

Output:

2D Numpy Array
[[11 12 13 22]
[21 7 23 14]
[31 10 33 7]]

Sorting 2D Numpy Array by row at index position 1

So we are going to use the above example to show how we sort an array by row.

import numpy as np

# Create a 2D Numpy array list of list
arr2D = np.array([[21, 22, 23, 20], [21, 17, 13, 14], [13, 10, 33, 19]])
print('2D Numpy Array')
print(arr2D)
# Sort 2D numpy array by 2nd row
sortedArr = arr2D [ :, arr2D[1].argsort()]
print('Sorted 2D Numpy Array')
print(sortedArr)

Output:

2D Numpy Array
[[21 22 23 20]
[21 17 13 14]
[13 10 33 19]]

Sorted 2D Numpy Array
[[23 20 22 21]
[13 14 17 21]
[33 19 10 13]]

So you can see that it changed column value, as we selected row at given index position using [] operator and using argsort()we got sorted indices after that we have changed the position of the column to sort our row.

Sorting 2D Numpy Array by the Last Row

import numpy as np

# Create a 2D Numpy array list of list
arr2D = np.array([[21, 22, 23, 20], [21, 17, 13, 14], [13, 10, 33, 19]])
print('2D Numpy Array')
print(arr2D)
# Sort 2D numpy array by last row
sortedArr = arr2D[:, arr2D[-1].argsort()]
print('Sorted 2D Numpy Array')
print(sortedArr)

Output:

2D Numpy Array
[[21 22 23 20]
[21 17 13 14]
[13 10 33 19]]

Sorted 2D Numpy Array
[[22 21 20 23]
[17 21 14 13]
[10 13 19 33]]

Conclusion:

So in this article, I have shown you different ways to sorting 2D Numpy Array by column or row in Python.

Happy learning guys!

Sorting 2D Numpy Array by column or row in Python | How to sort the NumPy array by column or row in Python? Read More »

Count occurrences of a value in NumPy array in Python

Count occurrences of a value in NumPy array in Python | numpy.count() in Python

Count Occurences of a Value in Numpy Array in Python: In this article, we have seen different methods to count the number of occurrences of a value in a NumPy array in Python. Check out the below given direct links and gain the information about Count occurrences of a value in a NumPy array in Python.

Python numpy.count() Function

The function of numpy.count()in python aid in the counts for the non-overlapping occurrence of sub-string in the specified range. The syntax for phyton numpy.count() function is as follows:

Syntax:

numpy.core.defchararray.count(arr, substring, start=0, end=None)

Parameters:

  • arr: array-like or string to be searched.
  • substring: substring to search for.
  • start, end: [int, optional] Range to search in.

Returns:

An integer array with the number of non-overlapping occurrences of the substring.

Example Code for numpy.count() Function in Python

numpy.count() function in python

# Python Program illustrating 
# numpy.char.count() method 
import numpy as np 
  
# 2D array 
arr = ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz']
  
print ("arr : ", arr)
  
print ("Count of 'Aa'", np.char.count(arr, 'Aa'))
print ("Count of 'Aa'", np.char.count(arr, 'Aa', start = 8))

Output:

arr : ['vdsdsttetteteAAAa', 'AAAAAAAaattttds', 'AAaaxxxxtt', 'AAaaXDSDdscz']

Count of 'Aa' [1 1 1 1]
Count of 'Aa' [1 0 0 0]

Also Check:

How to count the occurrences of a value in a NumPy array in Python

Counting the occurrences of a value in a NumPy array means returns the frequency of the value in the array. Here are the various methods used to count the occurrences of a value in a python numpy array.

Use count_nonzero()

We use the count_nonzero()function to count occurrences of a value in a NumPy array, which returns the count of values in a given numpy array. If the value of the axis argument is None, then it returns the count.

Let’s take an example, count all occurrences of value ‘6’ in an array,

import numpy as np
arr = np.array([9, 6, 7, 5, 6, 4, 5, 6, 5, 4, 7, 8, 6, 6, 7])
print('Numpy Array:')
print(arr)
# Count occurrence of element '3' in numpy array
count = np.count_nonzero(arr == 6)
print('Total occurences of "6" in array: ', count)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Numpy Array:
[9 6 7 5 6 4 5 6 5 4 7 8 6 6 7]
Total occurences of "6" in array: 5

In the above example, you have seen that we applied a condition to the numpy array ie., arr==6, then it applies the condition on each element of the array and stores the result as a bool value in a new array.

Use sum()

In this, we are using thesum()function to count occurrences of a value in an array.

import numpy as np
arr = np.array([9, 6, 7, 5, 6, 4, 5, 6, 5, 4, 7, 8, 6, 6, 7])
print('Numpy Array:')
print(arr)
# Count occurrence of element '6' in numpy array
count = (arr == 6).sum()

print('Total occurences of "6" in array: ', count)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Numpy Array: [9 6 7 5 6 4 5 6 5 4 7 8 6 6 7]
Total occurences of "6" in array: 5

In the above example, we have seen if the given condition is true then it is equivalent to one in python so we can add the True values in the array to get the sum of values in the array.

Use bincount()

We usebincount()function to count occurrences of a value in an array.

import numpy as np
arr = np.array([9, 6, 7, 5, 6, 4, 5, 6, 5, 4, 7, 8, 6, 6, 7])
count_arr = np.bincount(arr)
# Count occurrence of element '6' in numpy array
print('Total occurences of "6" in array: ', count_arr[6])
# Count occurrence of element '5' in numpy array
print('Total occurences of "5" in array: ', count_arr[5])

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Total occurences of "6" in array: 5
Total occurences of "5" in array: 3

Convert numpy array to list and count occurrences of a value in an array

In this method, first we convert the array to a list and then we applycount()function on the list to get the count of occurrences of an element.

import numpy as np
arr = np.array([9, 6, 7, 5, 6, 4, 5, 6, 5, 4, 7, 8, 6, 6, 7])
# Count occurrence of element '6' in numpy array
count = arr.tolist().count(6)
print('Total occurences of "6" in array: ', count)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Total occurences of "6" in array:

Select elements from the array that matches the value and count them

We can choose only those elements from the numpy array that is similar to a presented value and then we can attain the length of this new array. It will furnish the count of occurrences of the value in the original array. For instance,

import numpy as np
# Create a 2D Numpy Array from list of lists
matrix = np.array( [[2, 3, 4],
                    [5, 3, 4],
                    [5, 3, 5],
                    [4, 7, 8],
                    [3, 6, 2]] )
# Count occurrence of element '3' in each column
count = np.count_nonzero(matrix == 3, axis=0)
print('Total occurrences  of "3" in each column of 2D array: ', count)

Output: 

Total occurrences of "3" in each column of 2D array: [1 3 0]

Count occurrences of a value in 2D NumPy Array

We can use the count_nonzero() function to count the occurrences of a value in a 2D array or matrix.

import numpy as np
# Create a 2D Numpy Array from list of lists
matrix = np.array( [[2, 3, 4],
                    [5, 3, 4],
                    [5, 6, 5],
                    [6, 7, 6],
                    [3, 6, 2]] )
# Count occurrence of element '6' in complete 2D Numpy Array
count = np.count_nonzero(matrix == 6)
print('Total occurrences of "6" in 2D array:')
print(count)

Output:

Total occurrences of "6" in 2D array: 4

Count occurrences of a value in each row of 2D NumPy Array

To count the occurrences of a value in each row of the 2D  array we will pass the axis value as 1 in the count_nonzero() function.

It will return an array containing the count of occurrences of a value in each row.

import numpy as np
# Create a 2D Numpy Array from list of lists
matrix = np.array( [[2, 3, 4],
                    [5, 3, 4],
                    [6, 6, 5],
                    [4, 7, 6],
                    [3, 6, 2]] )
# Count occurrence of element '6' in each row
count = np.count_nonzero(matrix == 6, axis=1)
print('Total occurrences  of "6" in each row of 2D array: ', count)

Output:

Total occurrences of "6" in each row of 2D array: [0 0 2 1 1]

Count occurrences of a value in each column of 2D NumPy Array

In order to count the occurrences of a value in each column of the 2D NumPy array transfer the axis value as 0 in thecount_nonzero()function. After that, it will result in an array including the count of occurrences of a value in each column. For instance,

import numpy as np
# Create a 2D Numpy Array from list of lists
matrix = np.array( [[2, 3, 4],
                    [5, 3, 4],
                    [5, 3, 5],
                    [4, 7, 8],
                    [3, 6, 2]] )
# Count occurrence of element '3' in each column
count = np.count_nonzero(matrix == 3, axis=0)
print('Total occurrences  of "3" in each column of 2D array: ', count)

Output:

Total occurrences of "3" in each column of 2D array: [1 3 0]

Count occurrences of a value in NumPy array in Python | numpy.count() in Python Read More »

How to sort a Numpy Array in Python

How to sort a Numpy Array in Python? | numpy.sort() in Python | Python numpy.ndarray.sort() Function

In this article, we are going to show you sorting a NumpyArray in descending and in ascending order or sorts the elements from largest to smallest value or smallest to largest value. Stay tuned to this page and collect plenty of information about the numpy.sort() in Python and How to sort a Numpy Array in Python?

Sorting Arrays

Giving arrays to an ordered sequence is called sorting. An ordered sequence can be any sequence like numeric or alphabetical, ascending or descending.

Python’s Numpy module provides two different methods to sort a numpy array.

numpy.ndarray.sort() method in Python

A member function of the ndarray class is as follows:

ndarray.sort(axis=-1, kind='quicksort', order=None)

This can be ordered through a numpy array object (ndarray) and it classifies the incorporated numpy array in place.

Do Check:

Python numpy.sort() method

One more method is a global function in the numpy module i.e.

numpy.sort(array, axis=-1, kind='quicksort', order=None)

It allows a numpy array as an argument and results in a sorted copy of the Numpy array.

Where,

Sr.No.Parameter & Description
1a

Array to be sorted

2axis

The axis along which the array is to be sorted. If none, the array is flattened, sorting on the last axis

3kind

Default is quicksort

4order

If the array contains fields, the order of fields to be sorted

Sort a Numpy Array in Place

The NumPy ndarray object has a function called sort() that we will use for sorting.

import numpy as np
# Create a Numpy array from list of numbers
arr = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
array = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
# Sort the numpy array inplace
array.sort()
print('Original Array : ', arr)
print('Sorted Array : ', array)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Original Array : [ 9 1 3 2 17 5 2 8 14]
Sorted Array : [ 1 2 2 3 5 8 9 14 17]

So in the above example, you have seen that usingarray.sort()we have sorted our array in place.

Sort a Numpy array in Descending Order

In the above method, we have seen that by default both numpy.sort() and ndarray.sort() sorts the numpy array in ascending order. But now, you will observe how to sort an array in descending order?

import numpy as np
# Create a Numpy array from list of numbers
arr = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
array = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
# Sort the numpy array inplace
array = np.sort(arr)[::-1]

# Get a sorted copy of numpy array (Descending Order)
print('Original Array : ', arr)
print('Sorted Array : ', array)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Original Array : [ 9 1 3 2 17 5 2 8 14]
Sorted Array : [17 14 9 8 5 3 2 2 1]

Sorting a numpy array with different kinds of sorting algorithms

While sorting sort() function accepts a parameter ‘kind’ that tells about the sorting algorithm to be used. If not provided then the default value is quicksort. To sort numpy array with another sorting algorithm pass this ‘kind’ argument.

import numpy as np
# Create a Numpy array from list of numbers
arr = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
array = np.array([9, 1, 3, 2, 17, 5,  2, 8, 14])
# Sort the numpy array using different algorithms

#Sort Using 'mergesort'
sortedArr1 = np.sort(arr, kind='mergesort')

# Sort Using 'heapsort'
sortedArr2 = np.sort(arr, kind='heapsort')

# Sort Using 'heapsort'
sortedArr3 = np.sort(arr, kind='stable')

# Get a sorted copy of numpy array (Descending Order)
print('Original Array : ', arr)

print('Sorted Array using mergesort: ', sortedArr1)

print('Sorted Array using heapsort : ', sortedArr2)

print('Sorted Array using stable : ', sortedArr3)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Original Array : [ 9 1 3 2 17 5 2 8 14]
Sorted Array using mergesort: [ 1 2 2 3 5 8 9 14 17]
Sorted Array using heapsort : [ 1 2 2 3 5 8 9 14 17]
Sorted Array using stable : [ 1 2 2 3 5 8 9 14 17]

Sorting a 2D numpy array along with the axis

numpy.sort() and numpy.ndarray.sort() provides an argument axis to sort the elements along the axis.
Let’s create a 2D Numpy Array.

import numpy as np
# Create a 2D Numpy array list of list

arr2D = np.array([[8, 7, 1, 2], [3, 2, 3, 1], [29, 32, 11, 9]])

print(arr2D)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
[[ 8 7 1 2]
[ 3 2 3 1]
[29 32 11 9]]

Now sort contents of each column in 2D numpy Array,

import numpy as np
# Create a 2D Numpy array list of list

arr2D = np.array([[8, 7, 1, 2], [3, 2, 3, 1], [29, 32, 11, 9]])
arr2D.sort(axis=0)
print('Sorted Array : ')
print(arr2D)

Output:

RESTART: C:/Users/HP/Desktop/article3.py
Sorted Array :
[[ 3 2 1 1]
[ 8 7 3 2]
[29 32 11 9]]

So here is our sorted 2D numpy array.

How to sort a Numpy Array in Python? | numpy.sort() in Python | Python numpy.ndarray.sort() Function Read More »

Python Convert Matrix or 2D Numpy Array to a 1D Numpy Array

Python: Convert Matrix / 2D Numpy Array to a 1D Numpy Array | How to make a 2d Array into a 1d Array in Python?

This article is all about converting 2D Numpy Array to a 1D Numpy Array. Changing a 2D NumPy array into a 1D array returns in an array containing the same elements as the original, but with only one row. Want to learn how to convert 2d Array into 1d Array using Python? Then, stay tuned to this tutorial and jump into the main heads via the available links shown below:

Convert 2D Numpy array / Matrix to a 1D Numpy array using flatten()

Python Numpy provides a function flatten() to convert an array of any shape to a flat 1D array.

Firstly, it is required to import the numpy module,

import numpy as np

Syntax:

ndarray.flatten(order='C')
ndarray.flatten(order='F')
ndarray.flatten(order='A')

Order: In which items from the array will be read

Order=’C’: It will read items from array row-wise

Order=’F’: It will read items from array row-wise

Order=’A’: It will read items from array-based on memory order

Suppose we have a 2D Numpy array or matrix,

[7 4 2]
[5 3 6]
[2 9 5]

Which we have to convert in a 1D array. Let’s use this to convert a 2D numpy array or matrix to a new flat 1D numpy array,

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# get a flatten 1D copy of 2D Numpy array
flat_array = arr.flatten()
print('1D Numpy Array:')
print(flat_array)

Output:

1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

If we made any changes in our 1D array it will not affect our original 2D array.

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# get a flatten 1D copy of 2D Numpy array
flat_array = arr.flatten()
print('1D Numpy Array:')
print(flat_array)
# Modify the flat 1D array
flat_array[0] = 50
print('Modified Flat Array: ')
print(flat_array)
print('Original Input Array: ')
print(arr)

Output:

1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

Modified Flat Array:
[50 4 2 5 3 6 2 9 5]

Original Input Array:
[[7 4 2]
[5 3 6]
[2 9 5]]

Also Check:

Convert 2D Numpy array to 1D Numpy array using numpy.ravel()

Numpy have  a built-in function ‘numpy.ravel()’ that accepts an array element as parameter and returns a flatten 1D array.

Syntax:

numpy.ravel(input_arr, order='C')

Let’s make use of this syntax to convert 2D array to 1D array,

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# Get a flattened view of 2D Numpy array
flat_array = np.ravel(arr)
print('Flattened 1D Numpy array:')
print(flat_array)

Output:

Flattened 1D Numpy array:
[7 4 2 5 3 6 2 9 5]

If we made any changes in our 1D array using numpy.ravel() it will also affect our original 2D array.

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# Get a flattened view of 2D Numpy array
flat_array = np.ravel(arr)
print('Flattened 1D Numpy array:')
print(flat_array)
# Modify the 2nd element  in flat array
flat_array[1] = 12
# Changes will be reflected in both flat array and original 2D array
print('Modified Flattened 1D Numpy array:')
print(flat_array)
print('2D Numpy Array:')
print(arr)

Output:

Flattened 1D Numpy array:
[7 4 2 5 3 6 2 9 5]
Modified Flattened 1D Numpy array:
[ 7 12 2 5 3 6 2 9 5]
2D Numpy Array:
[[ 7 12 2]
[ 5 3 6]
[ 2 9 5]]

Convert a 2D Numpy array to a 1D array using numpy.reshape()

Numpy provides a built-in function reshape() to convert the shape of a numpy array,

It accepts three arguments-

  • a: Array which we have to be reshaped
  • newshape: Newshape can be a tuple or integer
  • order: The order in which items from the input array will be used
import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])

# convert 2D array to a 1D array of size 9
flat_arr = np.reshape(arr, 9)
print('1D Numpy Array:')
print(flat_arr)

Output:

1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

In the above example, we have pass 9 as an argument because there were a total of 9 elements (3X3) in the 2D input array.

numpy.reshape() and -1 size

This function can be used when the input array is too big and multidimensional or we just don’t know the total elements in the array. In such scenarios, we can pass the size as -1.

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])

# convert 2D array to a 1D array without mentioning the actual size
flat_arr = np.reshape(arr, -1)
print('1D Numpy Array:')
print(flat_arr)

Output:

1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

numpy.reshape() returns a new view object if possible

With the help of reshape() function, we can view the input array and any modification done in the view object will be reflected in the original input too.

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
[5, 3, 6],
[2, 9, 5]])
flat_arr = np.reshape(arr,-1)
print('1D Numpy Array:')
print(flat_arr)
# Modify the element at the first row and first column in the 1D array
arr[0][0] = 11
print('1D Numpy Array:')
print(flat_arr)
print('2D Numpy Array:')
print(arr)

Output:

1D Numpy Array:
[7 4 2 5 3 6 2 9 5]

1D Numpy Array:
[11 4 2 5 3 6 2 9 5]

2D Numpy Array:

[[11 4 2]
[ 5 3 6]
[ 2 9 5]]

Convert 2D Numpy array to 1D array but Column Wise

If we pass the order parameter in reshape() function as “F” then it will read 2D input array column-wise. As we will show below-

import numpy as np
# Create a 2D numpy array from list of lists
arr = np.array([[7, 4, 2],
                [5, 3, 6],
                [2, 9, 5]])
# Read 2D array column by column and create 1D array from it
flat_arr = np.reshape(arr, -1, order='F')
print('1D Numpy Array:')
print(flat_arr)

Output:

1D Numpy Array:
[7 5 2 4 3 9 2 6 5]

Python: Convert Matrix / 2D Numpy Array to a 1D Numpy Array | How to make a 2d Array into a 1d Array in Python? Read More »

numpy.amin() Find minimum value in Numpy Array and it’s index

numpy.amin() | Find minimum value in Numpy Array and it’s index | Python Numpy amin() Function

In this tutorial, we have shared the numpy.amin() statistical function of the Numpy library with its syntax, parameters, and returned values along with a few code examples to aid you in understanding how this function works. Also, you can easily find the minimum value in Numpy Array and its index using Numpy.amin() with sample programs.

numpy.amin()

The numpy.amin() function returns minimum value of an array. Also, it is a statistical function of the NumPy library that is utilized to return the minimum element of an array or minimum element along an axis.

Syntax:

The syntax needed to use this function is as follows:

numpy.amin(a, axis=None, out=None, keepdims=<no value>, initial=<no value>)

In this, we will pass two arguments-

where

  • a: It is the array from where we have to find min value
  • axis: It is optional and if not provided then it will pass the NumPy array and returns the min value.
    • If it’s given then it will return for an array of min values along the axis i.e.
    • In the case of axis=0 then it returns an array containing min value for each column.
    • In the case of axis=1 then it returns an array containing min value for each row.

Parameters:

Now it’s time to explain the parameters of this method:

  • a: This parameter shows the input data that is in the form of an array.
  • axis: It is an optional parameter registering the Axis or axes along which to operate. The value of this parameter can be int or a tuple of int values and also has a default value as None.
  • out: This optional parameter is applied to show an alternative output array in which the result becomes stored. The value of this parameter is in the form of an ndarray.
  • keepdims: By this optional parameter(having boolean value), the result will broadcast perfectly against the input array. If this option is set to True, the axes which are overcome are left in the result as dimensions with size one.
  • initial: This is a scalar and optional parameter used to show the maximum value of an output element.
  • where: This is an optional parameter used to indicate the elements to compare for the value.

Return Value:

The minimum of an array – arr[ndarray or scalar], scalar if the axis is None; the result is an array of dimension a.ndim – 1 if the axis is mentioned.

Also Refer:

Example on NumPy amin() Function

a = np.arange(9).reshape((3,3))

print("The Array is :")
print(a)

print("Minimum element in the array is:",np.amin(a))         

print("Minimum element along the first axis of array is:",np.amin(a, axis=0))  

print("Minimum element along the second axis of array is:",np.amin(a, axis=1))

Output:

The Array is : [[0 1 2] [3 4 5] [6 7 8]]

Minimum element in the array is: 0

Minimum element along the first axis of array is: [0 1 2]

Minimum element along the second axis of array is: [0 3 6]

Find the minimum value in a 1D Numpy Array

So now we are going to use numpy.amin() to find out the minimum element from a 1D array.

import numpy
arr = numpy.array([11, 12, 13, 14, 15, 16, 17, 15, 11, 12, 14, 15, 16, 17])
# Get the minimum element from a Numpy array
minElement = numpy.amin(arr)
print('Minimum element from Numpy Array : ', minElement)

Output:

Minimum element from Numpy Array : 11

Find minimum value & its index in a 2D Numpy Array

So here we are going to find out the min value in the 2D array.

import numpy
arr2D = numpy.array([[11, 12, 13],
                     [14, 15, 16],
                     [17, 15, 11],
                     [12, 14, 15]])# Get the minimum element from a Numpy array
minElement = numpy.amin(arr2D)
print('Minimum element from Numpy Array : ', minElement)

Output:

Minimum element from Numpy Array : 11

Find min values along the axis in 2D numpy array | min in rows or columns:

If we pass axis=0 then it gives an array containing min of every column,

import numpy
arr2D = numpy.array([[11, 12, 13],
                     [14, 15, 16],
                     [17, 15, 11],
                     [12, 14, 15]])
# Get the minimum values of each column i.e. along axis 0
minInColumns = numpy.amin(arr2D, axis=0)
print('min value of every column: ', minInColumns)

Output:

min value of every column: [11 12 11]

If we pass axis=1 then it gives an array containing min of every row,

import numpy 
arr2D = numpy.array([[11, 12, 13],
                     [14, 15, 16], 
                      [17, 15, 11], 
                     [12, 14, 15]]) 
# Get the minimum values of each row i.e. along axis 1 
minInColumns = numpy.amin(arr2D, axis=1) 
print('min value of every column: ', minInColumns)

Output:

min value of every column: [11 14 11 12]

Find the index of minimum value from the 2D numpy array

So here we are going to discuss how to find out the axis and coordinate of the min value in the array.

import numpy
arr2D = numpy.array([[11, 12, 13],
                     [14, 15, 16],
                     [17, 15, 11],
                     [12, 14, 15]])
result = numpy.where(arr2D == numpy.amin(arr2D))
print('Tuple of arrays returned : ', result)
print('List of coordinates of minimum value in Numpy array : ')
# zip the 2 arrays to get the exact coordinates
listOfCordinates = list(zip(result[0], result[1]))
# travese over the list of cordinates
for cord in listOfCordinates:
    print(cord)

Output:

Tuple of arrays returned : (array([0, 2], dtype=int32), array([0, 2], dtype=int32))
List of coordinates of minimum value in Numpy array :
(0, 0)
(2, 2)

numpy.amin() & NaN

if there is a NaN in the given numpy array then numpy.amin() will return NaN as minimum value.

import numpy
arr = numpy.array([11, 12, 13, 14, 15], dtype=float)
arr[3] = numpy.NaN
print('min element from Numpy Array : ', numpy.amin(arr))

Output:

min element from Numpy Array : nan

numpy.amin() | Find minimum value in Numpy Array and it’s index | Python Numpy amin() Function Read More »

Python-How to pad strings with zero, space or some other character

Python: How to pad strings with zero, space or some other character?

In this tutorial, we are going to discuss how to do padding of strings using zero, space, or some other character. Also, you can get complete knowledge of the methods used for padding strings in Python. So, let’s get started on learning How to pad strings with Zero, Space, or some other character.

Types of Padding in Python

There are two types of padding:

  1. Left padding
  2. Right padding

1. Left padding of string in Python

Left padding means adding a given character on the left side of a string.

For Example – If we pad three zeros in string 6 i.e, ‘0006’, or if we pad three space in string i.e,’6′

numStr = "6"
print('Original String :', numStr)
# Left pad the string with 0 to make it's length 4
numStr = numStr.zfill(4)
print('Updated String :' , numStr)

Output:

Original String : 6
Updated String : 0006

So in the above example, we have used'string.zfill(s, width)'to pad a given string on the left with zeros (0).

Also Check:

Left pad a string with space using string.rjust()

In this, we are going to use string.rjust() to add space in a given string.

numStr = "6"
print('Original String :', numStr)
# Make string right justified of length 4 by padding 3 spaces to left
numStr = numStr.rjust(4, ' ')
print('Updated String :', numStr)

Output:

Original String : 6
Updated String :    6

Left pad a string with some character using string.rjust()

For adding any character to our string we will use string.rjust() and pass that character in it.

numStr = "6"
print('Original String :', numStr)
# Make string right justified of length 4 by padding 3 '-' to left
numStr = numStr.rjust(4, '-')
print('Updated String :', numStr)

Output:

Original String : 6
Updated String : ---6

2. Right padding of string in Python

Right padding means adding a given character on the right side of the string.

Example- If we have a number string i.e. “ram”. Now we want to convert this string of length 3 to a string of length 6 by,

  • Right padding three zeros to the string i.e. “ram000”
  • Right padding three-space to the string i.e. “ram “
  • Right padding three characters to the string i.e. “ram—“

Right pad a string with zeros using string.ljust()

string.ljust() is used for padding a given character to the right of string to make its a length equal to the given width.

numStr = "67"
print('Original String :', numStr)
# Make string left justified of length 5 by padding 3 0s to the right of it
numStr = numStr.ljust(5, '0')
print('Updated String :', numStr)

Output:

Original String : 67
Updated String : 67000

Right pad a string with space using string.ljust()

In this, we will use string.ljust() to pad given character,

userName = "Shikha"
print('Original String :', userName)
# Make string left justified of length 7 by padding 3 spaces to the right of it
userName = userName.ljust(7, ' ')
print('Updated String :' , userName, 'is')

Here 3 spaces are padded to the right of the given string to make its length 9.

Output:

Original String : Shikha
Updated String : Shikha   is

Right pad a string with some character using string.ljust()

We can pass a character in string.ljust(s, width[, fillchar]) to right pad the given string by that passed character.

userName = "shikha"
print('Original String :', userName)
# Make string left justified of length 7 by padding 3 '-' to the right of it
userName = userName.ljust(7, '-')
print('Updated String :' , userName)

Output:

Here, three ‘-‘ are padded to the right of the given string to make its length 9.

Original String : shikha
Updated String : shikha---

Conclusion:

In this article, you have seen that how to do padding of strings using zero, space, or some other character.

Thank you!

Python: How to pad strings with zero, space or some other character? Read More »

Count Occurrences of a Single or Multiple Characters in String and Find their Index Positions

Count Occurrences of a Single or Multiple Characters in String and Find their Index Positions

A Python string is a collection of characters surrounded by single, double, or triple quotes. The computer does not understand the characters; instead, it stores the manipulated character as a combination of 0’s and 1’s internally.

In this article we are going to count single characters /multiple characters in a given string.

Examples:

1)Count occurrences of single characters in a given string

Input: 

given_string="btechgeeks" character ='e'

Output:

count of  e is : 3

2)Count occurrences of multiple characters in a  given string

Input:

given_string="btechgeeks" character =['e' , 'c' , 's' ]

Output:

count of  e is : 3
count of  c is : 1
count of  s is : 1

Count occurrences of single/multiple characters in a given string and indices of them

There are several methods  some of them are:

Method #1:Using count() function

The count() method in the string class returns the number of times a substring appears in the string. In simple terms, the count() method looks for a substring in a string and returns the number of times it appears.

1)Count occurrence of single character using count() function

We can count the occurrence of single character using count() as given below.

Below is the implementation:

# given string
string = "btechgeeks"
# given character which should be counted
character = 'e'
# counting the number of occurences of given character in the string
charcount = string.count(character)
print("count of ", character, "is :", charcount)

Output:

count of  e is : 3

2)Count occurrence of multiple characters using count() function

  • Traverse the list of characters whose frequency is to be calculated.
  • Using count function print the frequency of respective characters.

Below is the implementation:

# given string
string = "btechgeeks"
# given characters list which should be counted
charlist = ['e', 'c', 's']
# traverse the charlist
for char in charlist:
    # counting the number of occurences of given character in the string
    charcount = string.count(char)
    print("count of ", char, "is :", charcount)

Output:

count of  e is : 3
count of  c is : 1
count of  s is : 1

Method #2:Using Counter() function which is in collections module

Counter is a set and dict subset. Counter() takes an iterable entity as an argument and stores the elements as keys and the frequency of the elements as a value. So, in collections, if we transfer a string. When you call Counter(), you’ll get a Counter class object with characters as keys and their frequency in a string as values.

Counter() returns a Counter type object (a subclass of dict) with all characters in the string as keys and their occurrence count as values. We’ll use the [] operator to get the occurrence count of the character’s’ from it.

1)Count occurrence of single character using Counter() function

Counting the frequency of character using Counter() function

Below is the implementation:

from collections import Counter
# given string
string = "btechgeeks"
# given character which should be counted
character = 'e'
# counting the frequency of all characters using counter() function
freq = Counter(string)
# counting the number of occurences of given character in the string using [] operator
charcount = freq[character]
print("count of ", character, "is :", charcount)

Output:

count of  e is : 3

2)Count occurrence of multiple characters using Counter() function

  • Traverse the list of characters whose frequency is to be calculated.
  • We can count their frequency using [] operator

Below is the implementation:

from collections import Counter
# given string
string = "btechgeeks"
# given characters list which should be counted
charlist = ['e', 'c', 's']
# counting the frequency of all characters using counter() function
freq = Counter(string)
# traverse the charlist
for char in charlist:
    # counting the number of occurences of given character in the string using [] operator
    charcount = freq[char]
    print("count of ", char, "is :", charcount)

Output:

count of  e is : 3
count of  c is : 1
count of  s is : 1

Finding single character index positions in a string

Method #3:Using regex to count and print indices of occurrences of a string

Build a regex pattern that matches the character to find the index positions of that character in a string. Then iterate through all of the pattern matches in the string, adding their index positions to a list.

Below is the implementation:

import re
# given main string
string = 'Hello this is BTechGeeks'
# given character
char = 'e'
# Make a regex pattern that matches the given character
pattern = re.compile(char)
# Iterate over all the matches of regex pattern
matchiterator = pattern.finditer(string)
# taking empty list
indexlist = []
# initializing count to 0
charcount = 0
for matchobject in matchiterator:
    indexlist.append(matchobject.start())
    charcount = charcount + 1
print("Count of given character ", char, "is :", charcount)
print("indices of given characters :", indexlist)

Output:

Count of given character  e is : 4
indices of given characters : [1, 16, 20, 21]

Related Programs:

Count Occurrences of a Single or Multiple Characters in String and Find their Index Positions Read More »

Count Uppercase Characters in a String

Python: Count Uppercase Characters in a String

A Python string is a collection of characters surrounded by single, double, or triple quotes. The computer does not understand the characters; instead, it stores the manipulated character as a combination of 0’s and 1’s internally.

In this article we are going to count the uppercase letters in the given string

Examples:

Input:

string = "BTechGeeks"

Output:

The given string contains 3 uppercase letters

Count Uppercase Characters in a String

There are several ways to count uppercase letters in the given string some of them are:

Method #1:Using sum() + isupper() function

Using a generator expression, we can iterate over all of the characters in a string. If an uppercase character is discovered during iteration, pass it to the sum() function. Finally, the sum() function returns the total number of uppercase characters in a string.

Below is the implementation:

# given string
string = "BTechGeeks"
# counting uppercase letters in the given string
upper_count = sum(1 for element in string if element.isupper())
# print the count of uppercase letters
print("The given string contains", upper_count, "uppercase letters")

Output:

The given string contains 3 uppercase letters

Method #2:Using for loop

Using a for loop, we can iterate over a string character by character, counting the number of uppercase characters in the string as we go.

Below is the implementation:

# given string
string = "BTechGeeks"
# counting uppercase letters in the given string
upper_count = 0
# traverse the string using for loop
for element in string:
    # checking if the character is in uppercase
    if element.isupper():
      # increase the count if the given letter is upper
        upper_count += 1
# print the count of uppercase letters
print("The given string contains", upper_count, "uppercase letters")

Output:

The given string contains 3 uppercase letters

Method #3:Using List Comprehension

Iterate over all the characters in a string using list comprehension to create a list of only uppercase characters from the string. Then, by obtaining the size of that uppercase character list, we can obtain the number of uppercase characters in the string.

Below is the implementation:

# given string
string = "BTechGeeks"
# counting uppercase letters in the given string using list comprehension
upper_count = len([element for element in string if element.isupper()])
# print the count of uppercase letters
print("The given string contains", upper_count, "uppercase letters")

Output:

The given string contains 3 uppercase letters

Method #4:Using regex

With a pattern that matches all uppercase characters in the string, we can use Python’s regex module’s findall() method. findall() returns a list of all matches in the string, which in our case will be upper case characters. Then, by retrieving the size of that uppercase character list, we can calculate the number of uppercase characters in the string.

Below is the implementation:

import re
# given string
string = "BTechGeeks"
# counting uppercase letters in the given string using regex
upper_count = len(re.findall(r'[A-Z]', string))
# print the count of uppercase letters
print("The given string contains", upper_count, "uppercase letters")

Output:

The given string contains 3 uppercase letters

Related Programs:

Python: Count Uppercase Characters in a String Read More »