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

Sorting 2D 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!

Pandas: 6 Different ways to iterate over rows in a Dataframe & Update while iterating row by row

Pandas- 6 Different ways to iterate over rows in a Dataframe & Update while iterating row by row

In this tutorial, we will review & make you understand six different techniques to iterate over rows. Later we will also explain how to update the contents of a Dataframe while iterating over it row by row.

Let’s first create a dataframe which we will use in our example,

import pandas as pd
empoyees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])
print(empDfObj)

Output:

Name  Age    City        Experience
a  Shikha 34     Mumbai  5
b Rekha   31     Delhi      7
c Shishir  16     Punjab   11

Iterate over rows of a dataframe using DataFrame.iterrows()

Dataframe class implements a member function iterrows() i.e. DataFrame.iterrows(). Now, we will use this function to iterate over rows of a dataframe.

DataFrame.iterrows()

DataFrame.iterrows() returns an iterator that iterator iterate over all the rows of a dataframe.

For each row, it returns a tuple containing the index label and row contents as series.

Let’s use it in an example,

import pandas as pd
empoyees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

for (index_label, row_series) in empDfObj.iterrows():
   print('Row Index label : ', index_label)
   print('Row Content as Series : ', row_series.values)

Output:

Row Index label : a
Row Content as Series : ['Shikha' 34 'Mumbai' 5]
Row Index label : b
Row Content as Series : ['Rekha' 31 'Delhi' 7]
Row Index label : c
Row Content as Series : ['Shishir' 16 'Punjab' 11]

Note:

  • Do Not Preserve the data types as iterrows() returns each row contents as series however it doesn’t preserve datatypes of values in the rows.
  • We can not able to do any modification while iterating over the rows by iterrows(). If we do some changes to it then our original dataframe would not be affected.

Iterate over rows of a dataframe using DataFrame.itertuples()

DataFrame.itertuples()

DataFrame.itertuples() yields a named tuple for each row containing all the column names and their value for that row.

Let’s use it,

import pandas as pd
empoyees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

# Iterate over the Dataframe rows as named tuples
for namedTuple in empDfObj.itertuples():
   #Print row contents inside the named tuple
   print(namedTuple)

Output:

Pandas(Index='a', Name='Shikha', Age=34, City='Mumbai', Experience=5)
Pandas(Index='b', Name='Rekha', Age=31, City='Delhi', Experience=7)
Pandas(Index='c', Name='Shishir', Age=16, City='Punjab', Experience=11)

So we can see that for every row it returned a named tuple. we can access the individual value by indexing..like,

For the first value,

namedTuple[0]

For the second value,

namedTuple[1]

Do Read:

Named Tuples without index

If we pass argument ‘index=False’ then it only shows the named tuple not the index column.

import pandas as pd
empoyees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

# Iterate over the Dataframe rows as named tuples without index
for namedTuple in empDfObj.itertuples(index=False):
   # Print row contents inside the named tuple
   print(namedTuple)

Output:

Pandas(Name='Shikha', Age=34, City='Mumbai', Experience=5)
Pandas(Name='Rekha', Age=31, City='Delhi', Experience=7)
Pandas(Name='Shishir', Age=16, City='Punjab', Experience=11)

Named Tuples with custom names

If we don’t want to show Pandas name every time, we can pass custom names too:

import pandas as pd
empoyees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(empoyees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

# Give Custom Name to the tuple while Iterating over the Dataframe rows
for row in empDfObj.itertuples(name='Employee'):
   # Print row contents inside the named tuple
   print(row)

Output:

Employee(Index='a', Name='Shikha', Age=34, City='Mumbai', Experience=5)
Employee(Index='b', Name='Rekha', Age=31, City='Delhi', Experience=7)
Employee(Index='c', Name='Shishir', Age=16, City='Punjab', Experience=11)

Iterate over rows in dataframe as Dictionary

Using this method we can iterate over the rows of the dataframe and convert them to the dictionary for accessing by column label using the same itertuples().

import pandas as pd
employees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(employees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

# itertuples() yields an iterate to named tuple
for row in empDfObj.itertuples(name='Employee'):
   # Convert named tuple to dictionary
   dictRow = row._asdict()
   # Print dictionary
   print(dictRow)
   # Access elements from dict i.e. row contents
   print(dictRow['Name'] , ' is from ' , dictRow['City'])

Output:

{'Index': 'a', 'Name': 'Shikha', 'Age': 34, 'City': 'Mumbai', 'Experience': 5}
Shikha is from Mumbai
{'Index': 'b', 'Name': 'Rekha', 'Age': 31, 'City': 'Delhi', 'Experience': 7}
Rekha is from Delhi
{'Index': 'c', 'Name': 'Shishir', 'Age': 16, 'City': 'Punjab', 'Experience': 11}
Shishir is from Punjab

Iterate over rows in dataframe using index position and iloc

We will loop through the 0th index to the last row and access each row by index position using iloc[].

import pandas as pd
employees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(employees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

# Loop through rows of dataframe by index i.e. from 0 to number of rows
for i in range(0, empDfObj.shape[0]):
   # get row contents as series using iloc{] and index position of row
   rowSeries = empDfObj.iloc[i]
   # print row contents
   print(rowSeries.values)

Output:

['Shikha' 34 'Mumbai' 5]
['Rekha' 31 'Delhi' 7]
['Shishir' 16 'Punjab' 11]

Iterate over rows in dataframe in reverse using index position and iloc

Using this we will loop through the last index to the 0th index and access each row by index position using iloc[].

import pandas as pd
employees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(employees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

# Loop through rows of dataframe by index in reverse i.e. from last row to row at 0th index.
for i in range(empDfObj.shape[0] - 1, -1, -1):
   # get row contents as series using iloc{] and index position of row
   rowSeries = empDfObj.iloc[i]
   # print row contents
   print(rowSeries.values)

Output:

['Shishir' 16 'Punjab' 11]
['Rekha' 31 'Delhi' 7]
['Shikha' 34 'Mumbai' 5]

Iterate over rows in dataframe using index labels and loc[]

import pandas as pd
employees = [('Shikha', 34, 'Mumbai', 5) ,
           ('Rekha', 31, 'Delhi' , 7) ,
           ('Shishir', 16, 'Punjab', 11)
            ]
# Create a DataFrame object
empDfObj = pd.DataFrame(employees, columns=['Name', 'Age', 'City', 'Experience'], index=['a', 'b', 'c'])

# loop through all the names in index label sequence of dataframe
for index in empDfObj.index:
   # For each index label, access the row contents as series
   rowSeries = empDfObj.loc[index]
   # print row contents
   print(rowSeries.values)

Output:

['Shikha' 34 'Mumbai' 5]
['Rekha' 31 'Delhi' 7]
['Shishir' 16 'Punjab' 11]

Update contents a dataframe While iterating row by row

As Dataframe.iterrows() returns a copy of the dataframe contents in a tuple, so updating it will have no effect on the actual dataframe. So, to update the contents of the dataframe we need to iterate over the rows of the dataframe using iterrows() and then access each row using at() to update its contents.

Let’s see an example,

Suppose we have a dataframe i.e

import pandas as pd


# List of Tuples
salaries = [(11, 5, 70000, 1000) ,
           (12, 7, 72200, 1100) ,
           (13, 11, 84999, 1000)
           ]
# Create a DataFrame object
salaryDfObj = pd.DataFrame(salaries, columns=['ID', 'Experience' , 'Salary', 'Bonus'])

Output:

   ID Experience Salary Bonus
0 11    5             70000 1000
1 12    7             72200 1100
2 13   11            84999 1000

Now we will update each value in column ‘Bonus’ by multiplying it with 2 while iterating over the dataframe row by row.

import pandas as pd


# List of Tuples
salaries = [(11, 5, 70000, 1000) ,
           (12, 7, 72200, 1100) ,
           (13, 11, 84999, 1000)
           ]
# iterate over the dataframe row by row
salaryDfObj = pd.DataFrame(salaries, columns=['ID', 'Experience' , 'Salary', 'Bonus'])
for index_label, row_series in salaryDfObj.iterrows():
   # For each row update the 'Bonus' value to it's double
   salaryDfObj.at[index_label , 'Bonus'] = row_series['Bonus'] * 2
print(salaryDfObj)

Output:

    ID    Experience Salary Bonus
0 11          5           70000 2000
1 12          7           72200 2200
2 13        11           84999 2000

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:

So in this article, you have seen different ways to iterate over rows in a dataframe & update while iterating row by row. Keep following our BtechGeeks for more concepts of python and various programming languages too.

CPP 11 Multithreading – Part 2: Joining and Detaching Threads | std::thread::join() & std::thread::detach() Methods with Examples

CPP 11 Multithreading – Part 2- Joining and Detaching Threads

In the previous article, we have discussed about How to trim strings in C++ using Boost String Algorithm Library. Let us learn how to find Multithreading – Part 2 in C++ Program.

Let’s discover this tutorial for getting more knowledge about C++11 Multithreading Part-2.  Here we are going to learn what is joining and detaching threads of std::thread. Apart from that, you may also see the explanation of std::thread::join() & std::thread::detach() Methods with Examples. So, stay tuned to this tutorial easily via available quick links.

Joining Threads with std::thread::join()

When the first thread is started then the other thread that is going to start yet should wait for the first thread to finish. For this, another we need to call the join() function on the std::thread object.

Syntax:

std::thread th(funcPtr);

// Some Code

th.join();

Suppose Main Thread has to start 10 Worker Threads and after starting all these threads, the main function will wait for them to finish. After joining all the threads the main function will continue.

So, let’s take an example. There is one main thread and some worker threads after joining all the threads the main function will continue. The main function will wait for them to finish.

#include <iostream>
#include <thread>
#include <algorithm>
#include <vector>
#include <functional>
class WorkerThread
{
public:
    void operator()()     
    {
        std::cout<<"Worker Thread "<<std::this_thread::get_id()<<" is Executing"<<std::endl;
    }
};
int main()  
{
    std::vector<std::thread> threadList;
    for(int i = 0; i < 10; i++)
    {
        threadList.push_back( std::thread( WorkerThread() ) );
    }
    // Now wait for all the worker thread to finish i.e.
    // Call join() function on each of the std::thread object
    std::cout<<"wait for all the worker thread to finish"<<std::endl;
    std::for_each(threadList.begin(),threadList.end(), std::mem_fn(&std::thread::join));
    std::cout<<"Exiting from Main Thread"<<std::endl;
    return 0;
}

Detaching Threads using std::thread::detach()

Detached threads are background threads sometimes also called daemon threads. To detach a thread we need to call std::detach() function on std::thread object. ie.,

std::thread th(funcPtr);
th.detach();

Once you call the detach(), then the std::thread object is no longer connected with the actual thread of execution.

Also Check:

Be cautious with calling detach() and join() on Thread Handles

We have to be careful on calling detach() and join() on thread handles. We are going to discuss some cases below for this:

Case 1: Never call join() or detach() on std::thread object with no associated executing thread

std::thread threadObj( (WorkerThread()) );
   threadObj.join();
   threadObj.join(); // It will cause Program to Terminate

When a join() function called on a thread object, join returns 0 then that ‘td::thread’ object has no associated thread with it. If the join() function again called on such an object then it will cause the program to Terminate. Similarly, detach() function will work.

Syntax:

std::thread threadObj( (WorkerThread()) );
   threadObj.detach();
   threadObj.detach(); // It will cause Program to Terminate

Before calling join() or detach() we should check if the thread is join-able every time or not,

std::thread threadObj( (WorkerThread()) );
   if(threadObj.joinable())
   {
       std::cout<<"Detaching Thread "<<std::endl;
       threadObj.detach();
   }
   if(threadObj.joinable())    
   {
       std::cout<<"Detaching Thread "<<std::endl;
       threadObj.detach();
   }
   
   std::thread threadObj2( (WorkerThread()) );
   if(threadObj2.joinable())
   {
       std::cout<<"Joining Thread "<<std::endl;
       threadObj2.join();
   }
   if(threadObj2.joinable())    
   {
       std::cout<<"Joining Thread "<<std::endl;
       threadObj2.join();
   }

Case 2: Never forget to call either join or detach on a std::thread object with associated executing thread

In this case, if neither join nor detach is called with a ‘std::thread’ object that has associated executing thread then during that object’s destruct-or it will terminate the program.

#include <iostream>
#include <thread>
#include <algorithm>
class WorkerThread
{
public:
    void operator()()     
    {
        std::cout<<"Worker Thread "<<std::endl;
    }
};
int main()  
{
    std::thread threadObj( (WorkerThread()) );
    // Program will terminate as we have't called either join or detach with the std::thread object.
    // Hence std::thread's object destructor will terminate the program
    return 0;
}

Similarly, we should not forget to call either join() or detach() in case of exceptions.

To prevent this with we should use Resource Acquisition Is Initialization (RAII) which is show below,

#include <iostream>
#include <thread>
class ThreadRAII
{
    std::thread & m_thread;
    public:
        ThreadRAII(std::thread  & threadObj) : m_thread(threadObj)
        {
            
        }
        ~ThreadRAII()
        {
            // Check if thread is joinable then detach the thread
            if(m_thread.joinable())
            {
                m_thread.detach();
            }
        }
};
void thread_function()
{
    for(int i = 0; i < 10000; i++);
        std::cout<<"thread_function Executing"<<std::endl;
}
 
int main()  
{
    std::thread threadObj(thread_function);
    
    // If we comment this Line, then program will crash
    ThreadRAII wrapperObj(threadObj);
    return 0;
}

Conclusion:

In this article, we have discussed completely regarding C++11 Multithreading joining and detaching threads of std::thread and some risk cases. Thank you!

Different ways to Erase / Delete an element from a Set in C++ | set::erase() Function in C++

Different ways to Erase or Delete an element from a Set in C++

In this article, we will be going to discuss various ways to erase an element from a Set in C++.

erase() function is used to remove elements from a set from the specified range.

Here, std::set gives 3 overloaded version of erase() member function. So, we will learn them one by one clearly in this tutorial.

First, let’s take a string which we will use as an example,

#include <iostream>
#include <set>
#include <iterator>
#include <string>
#include <vector>

int main() {
   //Set Of Strings 
   std::set<std::string> setOfStrs = {"Good", "Morning", "say", "hello", "at", "Hi", "is", "from", "to"};
    // Printing Contents of Set
    std::copy (setOfStrs.begin(), setOfStrs.end(), std::ostream_iterator<std::string>(std::cout, ", "));
    std::cout<<std::endl;
    return 0;
}

Output:

Good, Hi, Morning, at, from, hello, is, say, to

Now we will remove elements from it in three different ways:

Let’s start with the first way of erase/ delete an element from a set in C++

Removing Element from set By Iterator

An element that has to be erased will be given in the iterator. Iterator is accepted by the overloaded version of erase() function which provided by ‘std::set’.

Syntax:

iterator erase (const_iterator position);

It renders the element close to the last deleted element. Let’s apply this to remove an element from the above set of strings i.e.,

#include <iostream>
#include <set>
#include <iterator>
#include <string>
#include <vector>

int main() {
  
   //Set Of Strings 
   std::set<std::string> setOfStrs = {"Good", "Morning", "say", "hello", "at", "Hi", "is", "from", "to"};
    
    // Search for element "is"
    std::set<std::string>::iterator it = setOfStrs.find("is");
    // Check if Iterator is valid
    if(it != setOfStrs.end())
    {
        // Deletes the element pointing by iterator it
        setOfStrs.erase(it);
    }
    // Printing Contents of Set
    std::copy (setOfStrs.begin(), setOfStrs.end(), std::ostream_iterator<std::string>(std::cout, ", "));
    std::cout<<std::endl;
    return 0;
}

Output:

Good, Hi, Morning, at, from, hello, say, to

So you have seen this is how we erase elements from the given string. You can see that above we have erased “is” from our given string.

Read More:

Removing Element from set By Value

“std::set” presents an overloaded version of an erase() function that allows a value and delete that from the set.

Syntax:

size_type erase (const value_type& val);

Let’s view the following example code on removing an element from the above set of strings i.e.,

#include <iostream>
#include <set>
#include <iterator> 
#include <string>
#include <vector>
int main() {
    //Set Of Strings 
    std::set<std::string> setOfStrs = {"Good", "Morning", "say", "hello", "at", "Hi", "is", "from", "to"};
    // Erase element "that" from set
    setOfStrs.erase("that");
    // Printing Contents of Set
    std::copy (setOfStrs.begin(), setOfStrs.end(), std::ostream_iterator<std::string>(std::cout, ", "));
    std::cout<<std::endl;
    return 0;
}

Output:

Good, Hi, Morning, at, from, hello, is, say, to

So above you can see that we remove ‘that’ from our string.

Removing Element from set By Iterator Range

In this approach, ‘std::set’ gives an overloaded version of erase() function that takes two iterators representing a range from (start) to (end -1).

Syntax:

iterator erase (const_iterator first, const_iterator last);

Now, we will use this to remove elements from the above set of strings i.e.,

#include <iostream>
#include <set>
#include <iterator> 
#include <string>
#include <vector>
int main() {
    //Set Of Strings 
    std::set<std::string> setOfStrs = {"Good", "Morning", "say", "hello", "at", "Hi", "is", "from", "to"};
    // Iterator pointing to "Hello" in Set
std::set<std::string>::iterator start = setOfStrs.find("Hello");
// Iterator pointing to "from" in Set
std::set<std::string>::iterator last = setOfStrs.find("from");
// Check if both start and last iterators are valid
if(start != setOfStrs.end() && last != setOfStrs.end())
{
    // Erase all elements from "Hello" to "from"
    setOfStrs.erase(start, last);
}

    return 0;
}

Output:

Good, Morning, say, to

So you can see that it has remove all the elements in the given range and returns the element next to the last deleted element.

Conclusion:

In this article, you have seen different ways to erase/delete an element from a Set in C++. Keep browsing our C++, CSS, HTML, Python articles on BtechGeeks and improve your coding skills more and more. Thank you!

Convert integer to string in Python

We can convert an integer data type using the python built-in str() function. This function takes any data type as an argument and converts it into a string. But we can also do it using the “%s” literal and using the .format() function.

How to convert an integer to a string in Python

Below is the list of possible ways to convert an integer to string in python:

1. Using str() function :

Syntax: str(integer_value)

Convert Integer to String in Python Using str() function
Output:
Convert Integer to String in Python Using str() function Output

2. Using “%s” keyword:

Syntax: “%s” % integer

Convert Integer to String in Python Using s keyword

Output:

Convert Integer to String in Python Using str() function Output
3. Using .format() function:

Syntax: ‘{}’.format(integer)

Convert Integer to String in Python Using format function
Output:

Using .format() function op

4. Using f-string:

Syntax: f'{integer}’

Convert-Integer-to-String-in-Python-Using-f-string
Output:

Convert Integer to String in Python Using f string output

Conclusion:

We have defined all methods of converting the integer data type to the string type. You can use one of them according to your requirement.

How to Convert a Python String to int

Convert Python String to Int:

To convert a string to integer in Python, use the int() function. This function takes two parameters: the initial string and the optional base to represent the data. In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.But use of the int() function is not the only way to do so. This type of conversion can also be done using thefloat() keyword, as a float value can be used to compute with integers.

Below is the list of possible ways to convert an integer to string in python:

1. Using int() function:

Syntaxint(string)

Example:

Using int() function

Output:

Using int() function output
As a side note, to convert to float, we can use float() in python:

Example:

use float() in python

Output:

use float() in python output
2. Using float() function:

We first convert to float, then convert float to integer. Obviously the above method is better (directly convert to integer).

Syntax: float(string)

Example:

Using-float-function

Output:

Using float() function output

If you have a decimal integer represented as a string and you want to convert the Python string to an int, then you just follow the above method (pass the string to int()), which returns a decimal integer.But By default, int() assumes that the string argument represents a decimal integer. If, however, you pass a hexadecimal string to int(), then you’ll see a ValueError

For value error

The error message says that the string is not a valid decimal integer.

When you pass a string to int(), you can specify the number system that you’re using to represent the integer. The way to specify the number system is to use base:

Now, int() understands you are passing a hexadecimal string and expecting a decimal integer.

Conclusion:

This article is all about how to convert python string to int.All methods are clearly explained here. Now I hope you’re comfortable with the ins and outs of converting a Python string to an int.

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

Count occurrences of a value in NumPy array 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]

MYSQL INSERT WITH SELECT

In this article we are going to discuss how to insert data into a table using select method in MYSQL.

MYSQL INSERT WITH SELECT: SINGLE TABLE

Select method copies data from one table and inserts into another table.

Syntax:

INSERT INTO table_name(column_name)
SELECT tbl_name.col_name
FROM some_table tbl_name
WHERE condition;

Lets take an example,here we will create a table employees_regist ,which will then select some data from an already existing table emplyees_details in our database.

emplyees_details table has columns emloyee_no, first_name, last_name and designation_post. To see all the rows in employees_details table we will do a SELECT * query on it.

SELECT * FROM employee_details;

After this query you will get this result,

Output:

+-------------+------------+-----------+------------+
| employee_no | first_name | last_name | desig_post |
+-------------+------------+-----------+------------+
|                    1 | Shikha       | Mishra       | Developer |
|                    2 | Ritika         | Mathur      | Designer   |
|                    3 | Rohan        | Rathour     | Developer |
|                    4 | Aarush       | Rathour     | Developer |
|                    5 | Aadhya      | Roopam    | Techwriter |
+-------------+------------+-----------+------------+

So you can see that we already have one table(employee_details), now we are going to create our new table ’employee_regist’.

CREATE TABLE employee_regist(
    employee_exp INT AUTO_INCREMENT,
    first_name VARCHAR(255),
    last_name VARCHAR(255),
    employee_post VARCHAR(255),
    employee_salary INT,
    PRIMARY KEY (employee_exp)
);

So you can see that we have created a table but there is no value because our table is empty at this time,if you want to see table you can write select query,

SELECT * FROM employee_regist;

Output:

Empty set (0.05 sec)

Now we are going to add values in employee_regist.For this we are going to write INSERT query.

INSERT INTOemployee_regist(emploee_exp,first_name,last_name ) 
 SELECT employee_no,first_name,last_name FROM employee_details 
 WHERE desig_post = 'Developer' ;

Now to show output we will execute our SELECT query ,

SELECT * FROM registration_details;

Output:

+-------------+------------+-----------+------------+
| employee_no | first_name | last_name | desig_post |
+-------------+------------+-----------+------------+
|                    1 | Shikha       | Mishra       | Developer |
|                    3 | Rohan        | Rathour     | Developer |
|                    4 | Aarush       | Rathour     | Developer ||
+-------------+------------+-----------+------------+

So in above table you have seen that all table not added only those satisfying the given condition were addaed.

MYSQL INSERT WITH SELECT: MULTIPLE TABLES

In above table you have seen that we have added rows and column from single table but you can also do the same with multiple table.Let’s see it by an example,

We have employee_regist,emplyee_details and eregistered_employee already present in our database,

Now we are going to execute SELECT query to see the data in these table one by one,

’employee_regist’

SELECT * FROM employee_regist;

Output:

+-------------+------------+-----------+------------+
| employee_no | first_name | last_name | confirm     |
+-------------+------------+-----------+------------+
|                      |                    |                  |                   |
|                      |                    |                  |                   |
|                      |                    |                  |                   |
+-------------+------------+-----------+------------+

’employee_details’

SELECT * FROM employee_details;

output:

+-------------+------------+-----------+------------+
| employee_no | first_name | last_name | desig_post |
+-------------+------------+-----------+------------+
|                    1 | Shikha       |  Mishra      | Developer |
|                    2 | Ritika         | Mathur      | Designer   |
|                    3 | Rohan        | Rathour     | Developer |
|                    4 | Aarush       | Rathour     | Developer |
|                    5 | Aadhya      | Roopam    | Techwriter |
+-------------+------------+-----------+------------+

’employee_status’

SELECT * FROM registered_employee;

Output:

+-------------+------------+-----------+------------+
|  first_name | last_name | confirm                            |
+-------------+------------+-----------+------------+
|         Shikha | Mishra     | yes                                    |
|           Ritika | Mathur    | yes                                    |
|          Rohan | Rathour   | No                                    |
|          Aarush| Rathour   |yes                                     |
|        Aadhya | Roopam  | No                                     |
+-------------+------------+-----------+------------+

Now we are going to write a query in MySQL to get the data into employee_regist from  employee_details and registered_employee.

Selecting first_name and last_name from employee_details and confirm from employee_registered of only those students who have ‘Developer‘ stream.

INSERT INTO employee_regist(employee_no,first_name,last_name, employee_confirm) 
SELECT em.employee_no,em.first_name,em.last_name ,re.confirm
FROM  employee_details em , confirm re
WHERE em.first_name = re.first_name 
AND em.last_name = re.last_name
AND em.stream_name = 'Developer'  ;

Above in our query we have used em and re as alias,So now we are going to see output It will add data from multiple table.

Output:

+————-+————+———–+————+
| employee_no | first_name | last_name | confirm |
+————-+————+———–+————+
| 1                    | Shikha       | Mishra      |yes          |
| 3                    | Rohan       | Rathour     |No          |
| 4                    | Aarush      | Rathour     |yes          |

+————-+————+———–+————+

Conclusion:

In this article we have discussed how to insert data into a single and multiple table using select method in MYSQL.

Thanks to all!

MySQL For Loop Example

In this article we will discuss about For Loop in MySQL with examples.

Loops in MySQL

Loop is a order of instructions that is continually replicated until a given condition is reached. MySQL also provides loop functionality like other languages.

Syntax:

label_for_loop: LOOP
IF <condition> THEN
LEAVE label_for_loop;
END IF;
<statements to be executed - separated by ';' >
ITERATE label_for_loop;
END LOOP;

Parameters:

1.labelname:It is an non-mandatory label at the start and end.

2.loop:For start and end loop.

3.statements:Condition which you give for execution

Flow of executions in For Loop:

MySQL for loop_images

MySQL For Loop Examples

Let’s understand it by example,

Example 1: Loop through and display the ‘%’ five times

DROP PROCEDURE IF EXISTS for_loop_star;
DELIMITER $$
CREATE procedure for_loop_star()
BEGIN
  DECLARE x INT;
  DECLARE percentage VARCHAR(50);
  DECLARE f_output VARCHAR(50);
  SET x = 1;
  SET star= "%";
  SET f_output ="";
  forloop: LOOP
    IF x > 5 THEN
    LEAVE forloop;
    END IF;
   SET x = x + 1;
   set f_output = CONCAT(f_output, percentage);
  END LOOP;
SELECT f_output;
END $$
DELIMITER ;
CALL for_loop_percentage();

In above code you can see that we have created a strategy for_loop_percentage() to run for loop to print the ‘%’ five times .Initial x value is 1,after every loop it increment by 1.Percentage concatenates with f_output in every iteration,after that checks the value of x, and if it is greater than five the loop will terminate.

Using SELECT f_output statement we will get our output.

Output:

f_output-
%%%%%

Example2:CREATE TABLE Mytable (value VARCHAR(50) NULL DEFAULT NULL);

DELIMITER $$ 
CREATE PROCEDURE ADD()
 BEGIN
  DECLARE a INT Default 1 ;
  simple_loop: LOOP     
    insert into table1 values(a);
    SET a=a+1;
    IF a=11 THEN
      LEAVE simple_loop;
    END IF;
 END LOOP simple_loop;
END $$

Queries to check the output –

CALL ADD();
Select value 
from Mytable;

Output:

1
2
3
4
5
6
7
8
9
10

Example3:

DELIMITER $$
CREATE FUNCTION Mydemo (value1 INT)
RETURNS INT
BEGIN
 DECLARE value2 INT;
 SET value2 = 0;
 label: LOOP
  SET income = value2 + value1 ;
  IF value2 < 4000 THEN
    ITERATE label;
  END IF;
  LEAVE label;
 END LOOP label;
 RETURN value2 ;
END $$
DELIMITER ;

Queries to check the output :

CALL Mydemo();

Input –

value1: 3500

Output –

value2: 3500

Conclusion:

In this article we have discussed about For Loop in MySQL with different examples.Thank you!

Create Temporary Table in MySQL

In this article we are going to discuss about how to create temporary table in MySQL.

MySQL has a property to create a temporary table where we can keep keep temporary data.MySQL can also delete this table automatically whenever current session is ended or the user stop the program. WE can also remove it manualy using Drop method.

In MySQL we can create temporary table using ‘Temporary’ keyword.

Create temporary table and insert data

Here we are going to create a temporary table and insert some data in it.

Syntax:

CREATE TEMPORARY TABLE temporary_table_name SELECT * FROM existing_table_name LIMIT 0;

So suppose we have an existing table ‘registration_details’,

MySQL create table_existing
Now we are going to create a new table with the help of our existing table ‘registration_details’ below is our query for this,

CREATE TEMPORARY TABLE registered_employee
SELECT first_name, desig_post FROM registration_details WHERE desig_post ="Developer"  AND last_name="Mishra" ;

Now by using below select query we will see our output,
select * from registered_employee;

MySQL create table_2
So you can see that we have got our output registered_employee having only those employee who have last_name =’mishra’ and desig_post=’developer’ as we have given condition.

Now we are going to add some data using insert query,let’s see how it will work

INSERT INTO registered_employee(first_name,desig_post)
SELECT first_name,desig_post
FROM registration_details
WHERE
desig_post="tester"
;

Here is our output:

MySQL insert table_3
In above query you can see that we have given condition desig_post=”tester” so it added those name having tester designation.

Create temporary table in a select statement without a separate create table

Now we are going to create a table using ‘AS’ keyword,below is the query for it.

CREATE TEMPORARY TABLE IF NOT EXISTS registered_employee AS 
 (SELECT first_name,desig_post  FROM registration_details 
 WHERE desig_post ="developer" & "tester");

Here is output:

MySQL insert table_3

Create a temporary table in MySQL with an index

Now we are going to create a temporary table with an index,

Syntax:

CREATE TEMPORARY TABLE temporary_table_name (index_column_name INTEGER NOT NULL AUTO_INCREMENT, PRIMARY
KEY(index_column_name), INDEX(index_column_name))
SELECT * FROM existing_table_name
WHERE  ;

Now let’s take an example to understand this,

CREATE TEMPORARY TABLE registered_employee_with_index (registration_number INTEGER NOT NULL AUTO_INCREMENT, PRIMARY    
KEY(registration_number), INDEX(registration_number))
SELECT * FROM registration_details
WHERE desig_post ="developer" ;

Here is our output:

MySQL create table_4
So you can see that above we have given condition that ‘WHERE desig_post =”developer”‘ and we got our new table “registered_employee_with_index” with index number.

Add a column to temporary table in MySQL

Here we are going to add a new column using Alter command in our temporary table,

Syntax:

ALTER TABLE temporary_table_name ADD new_column_name  
DEFAULT default_value;

Let’s take an example,

We will be use above table registered_employee_with_index and adding a new column state_name to it.

ALTER TABLE registered_employee_with_index ADD state_name varchar(255) 
DEFAULT 'Andhra Pradesh';

MySQL create table_5
You can see in the above output, a new column state_name got added to the table registered_employee_with_index.

Conclusion:

In this article we have discussed  about how to create temporary table in MySQL using different method.Thank you!