Convert number to binary c++ – C++ Program to Convert Decimal Number to Binary Number

C++ Program to Convert Decimal Number to Binary Number

Convert number to binary c++: In the previous article, we have discussed about C++ Program to Convert Binary Number to Decimal Number. Let us learn how to Convert Decimal Number to Binary Number in C++ Program.

Methods to Convert Decimal Numbers to Binary Numbers in C++

Convert decimal to binary c++: In this article, we discuss different methods by which we can convert decimal numbers to binary numbers in c++. The methods that we will discuss today are given below.

First, discuss the basic intuition behind converting decimal to binary numbers in c++. Suppose a number is 17 and we have to find a binary of 17 then we can do like this:-

17%2!=0     binary=1              17/2=8

8%2==0      binary=01            8/2=4

4%2==0      binary=001         4/2=2

2%2==0      binary=0001        2/2=1

1%2!=0        binary=10001       1/2=0

and we stop. So we get binary of a number like this. Now we will discuss different methods of doing this task.

Method 1-Using arithmetic operator with array

C++ convert decimal to binary: As we see in the example above we do the task in the same manner. First, we check whether the number is divisible by 2 or not. If it is divisible by 2 then we store 0 in the array else we will store 1 in the array. We do the same thing till our number is greater than 0. After that, we will print the elements of the array in the reverse form which will be the answer. Let’s write the code for this.

#include <iostream>
using namespace std;

void decimalToBinary(int n)
{
    int binaryNum[32],num=n;
    int i = 0;
    while (n > 0) {
        binaryNum[i] = n % 2;
        n = n / 2;
        i++;
    }
    cout<<num<<" in binary form is ";
    for (int j = i - 1; j >= 0; j--)
    {
        cout << binaryNum[j];
    }
}

int main()
{
    int n = 17;
    decimalToBinary(n);
    return 0;
}

Output

17 in binary form is 10001

Method 2-Using arithmetic operator without the array

C++ int to binary: We can also do the same task without using the array. Here the idea is the same but instead of an array, we use a variable. Let’s write the code for this.

#include <bits/stdc++.h>
using namespace std;

int decimalToBinary(int n)
{
     long long binaryNumber = 0;
    int rem, i = 1, step = 1;

    while (n!=0)
    {
        rem = n%2;
        n /= 2;
        binaryNumber += rem*i;
        i *= 10;
    }
    return binaryNumber;
}

int main()
{
    int n = 17;
    cout<<n<<" in binary form is "<<decimalToBinary(n);
    return 0;
}

Output

17 in binary form is 10001

Method 3-Using bitwise operator

Decimal to binary c++: We can use bitwise operators to do the above job. Note that bitwise operators work faster than arithmetic operators used above. Let’s write the code for this.

#include <bits/stdc++.h>
using namespace std;

int decimalToBinary(int n)
{
    cout<<n<<" in binary form is ";
    int l=log2(n);
    for (int i = l; i >= 0; i--) {
        int k = n >> i;
        if (k & 1)
            cout << "1";
        else
            cout << "0";
    }
}

int main()
{
    int n = 17;
    decimalToBinary(n);
    return 0;
}

Output

17 in binary form is 10001

So these are the methods to convert decimal numbers to binary number in c++.

Remove first column pandas – Pandas: Delete First Column of Dataframe in Python

Methods to delete the first column of a dataframe using Python

Remove first column pandas: In this article, we discuss different ways to delete the first column of a dataframe in pandas using python.

  • Method 1-Using drop() method

Drop first column pandas: This is one of the methods to delete the first columns of a dataframe in pandas using pandas.drop() method is used to delete or drop specified labels from rows or columns. Let see how the drop method works.

Syntax: DataFrame.drop(self, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=’raise’).

As our main task is to delete columns using this method so we have to remember some points. The first point is that the column we want to delete is to be given in the columns parameter of the drop() method. The second point is that we have to assign axis value 1 if we want to work with columns. Inplace is used if we want to make changes in the existing dataframe. If inplace is true changes will be made in the existing dataframe otherwise we have to store the dataframe in another variable. Let see this with an example.

import pandas as pd
import numpy as np
students = [('Raj', 24, 95) ,
            ('Rahul', 22,97) ,
            ('Aadi', 22,81) ,
            ('Abhay', 21,87) ,
            ('Ajjet', 21,74),
            ('Amar',22,76),
            ('Aman',20,76)]
# Create a DataFrame object
df = pd.DataFrame(  students, 
                    columns=['Name', 'Age','Marks'])
print("Original Dataframe\n")
print(df,'\n')
#Drop first column
df.drop(columns=df.columns[0], 
        axis=1, 
        inplace=True)
print("New Dataframe\n")
print(df)

Output

Original Dataframe

    Name  Age  Marks
0    Raj   24     95
1  Rahul   22     97
2   Aadi   22     81
3  Abhay   21     87
4  Ajjet   21     74
5   Amar   22     76
6   Aman   20     76 

New Dataframe

   Age  Marks
0   24     95
1   22     97
2   22     81
3   21     87
4   21     74
5   22     76
6   20     76

Here we see that we pass our first column by index in the drop method and the first column is successfully deleted. As we give inplace=True that’s why changes are made in the original dataframe.

  • Method 2- Using del keyword

Pandas remove first column: del keyword in python is used to delete objects. Objects can be variables, lists, etc. Here we normally use                    del df[df.columns[0]] to delete first column in dataframe. df. columns[0] give the name of the column at index 0 which is our column 1.As we get our column name so it is very easy to delete it using the del keyword. Here point to remember that df is our dataframe name. It is not compulsory to use df as a dataframe name. We can name the dataframe as per our wish Let see this with the help of an example.

import pandas as pd
import numpy as np
students = [('Raj', 24, 95) ,
            ('Rahul', 22,97) ,
            ('Aadi', 22,81) ,
            ('Abhay', 21,87) ,
            ('Ajjet', 21,74),
            ('Amar',22,76),
            ('Aman',20,76)]
# Create a DataFrame object
df = pd.DataFrame(  students, 
                    columns=['Name', 'Age','Marks'])
print("Original Dataframe\n")
print(df,'\n')
#Drop first column
del df[df.columns[0]]
print("New Dataframe\n")
print(df)

Output

Original Dataframe

    Name  Age  Marks
0    Raj   24     95
1  Rahul   22     97
2   Aadi   22     81
3  Abhay   21     87
4  Ajjet   21     74
5   Amar   22     76
6   Aman   20     76 

New Dataframe

   Age  Marks
0   24     95
1   22     97
2   22     81
3   21     87
4   21     74
5   22     76
6   20     76
  • Method 3-Using pop() method

Pandas drop first column: In Pandas, the dataframe provides a function pop(column_name). It expects a column name as an argument and deletes that column from the calling dataframe object. It also returns the deleted column as a series. Let’s use this to delete the first column of the dataframe. Let see this with the help of an example.

import pandas as pd
import numpy as np
students = [('Raj', 24, 95) ,
            ('Rahul', 22,97) ,
            ('Aadi', 22,81) ,
            ('Abhay', 21,87) ,
            ('Ajjet', 21,74),
            ('Amar',22,76),
            ('Aman',20,76)]
# Create a DataFrame object
df = pd.DataFrame(  students, 
                    columns=['Name', 'Age','Marks'])
print("Original Dataframe\n")
print(df,'\n')
#Drop first column
df.pop(df.columns[0])
print("New Dataframe\n")
print(df)

Output

Original Dataframe

    Name  Age  Marks
0    Raj   24     95
1  Rahul   22     97
2   Aadi   22     81
3  Abhay   21     87
4  Ajjet   21     74
5   Amar   22     76
6   Aman   20     76 

New Dataframe

   Age  Marks
0   24     95
1   22     97
2   22     81
3   21     87
4   21     74
5   22     76
6   20     76

So these are the methods to delete the first column of the dataframe in pandas using python. These methods can be used to remove some other columns also.

Iseven c++ – C++ Program to Check Whether Number is Even or Odd

C++ Program to Check Whether Number is Even or Odd

Iseven c++: In the previous article, we have discussed about C++ Program to Swap Two Numbers. Let us learn how to Check Whether Number is Even or Odd in C++ Program.

Different methods in c++ to check whether a number is even or odd

Iseven c++: In this article, we see different methods to checks whether a number is even or odd. If we see in brief an even number is a number that is divisible by 2 while an odd number is a number that is not divisible by 2. Let see different methods one by one to check this.

Method 1-Using if-else statement and modulus(%) operator

As we know that if a number is divisible by 2 then it is even otherwise it is odd. We can use the modulus(%) operator to find this. Modulus(%) operator gives the remainder when one number is divisible by another number. So if a number is even so on divisible by 2 gives remainder 0 otherwise if the number is odd it gives remainder 1. So we use this property to write our program. Let see the code for this.

#include <iostream>
using namespace std;

void isEven(int n)
{
    if(n%2==0)
    {
        cout<<"Number is even"<<endl;
    }
    else
    {
        cout<<"Number is odd"<<endl;
    }
}
int main() {
    int num1=10, num2=9;
    isEven(num1);
    isEven(num2);
    return 0;
}

Output

Number is even
Number is odd

Here we see that when we pass number 10 in the function we get the number is even and when we pass number 9 in the program we get the number is odd. Hence our program perfectly runs.

Method 2-Using ternary operator and modulus operator(%)

Ternary operators are a short and crisp way of using if-else statements in one line.

syntax :condition ? expression1 : expression2;

This is the syntax of the ternary operator. If the condition is true then statement 1 will get executed otherwise statement 2 will get executed.

Let write code for our program.

#include <iostream>
using namespace std;

void isEven(int n)
{
    n%2==0?cout<<"Number is even"<<endl:cout<<"Number is odd"<<endl;
}
int main() {
    int num1=10, num2=9;
    isEven(num1);
    isEven(num2);
    return 0;
}

Output

Number is even
Number is odd

We get the same output as we get in method 1 but this time our code is very short.

Method 3-Using bitwise and operator

In this method, we will see how can we use bitwise and operator to check whether a number is even or odd. First, let understand the logic. First, we write some numbers in binary form to analyze them.

1->1       2->10         3->11           4->100          5->101       6->110    7->111

So if we analyze the binary representation of these numbers we can see that the number which are odd have unit place as 1 in their binary representation and the numbers which even have unit place as 0 in their binary representation. So if we take bitwise and of even number, with 1 we always get output as 0 and if we take bitwise and of odd number with 1 we always get output is 1. So we can use this logic to write our program.

#include <iostream>
using namespace std;

void isEven(int n)
{
    if((n&1)==0)
    {
        cout<<"Number is even"<<endl;
    }
    else
    {
        cout<<"Number is odd"<<endl;
    }
}
int main() {
    int num1=10, num2=9;
    isEven(num1);
    isEven(num2);
    return 0;
}

Output

Number is even
Number is odd

So these are the methods to check whether a number is even or odd in c++.

Python max of dictionary – Python : How to Get all Keys with Maximum Value in a Dictionary

Method to get all the keys with maximum value in a dictionary in python

Python max of dictionary: In this article we will discuss about different methods to get all the keys with maximum value in a dictionary. Let us see all these methods one by one.

  • Method 1-Using max() function and d.get

Max value of dictionary python: As the name suggests max function is used to find the maximum value. Let us see what is max() function in python and how it works.

max() function

How to get max value in dictionary python: The max() function returns the item with the highest value or the item with the highest value in an iterable. Normally we pass iterables in the max() function to get the max value in iterable but as we know dictionary has both keys and values so we have to pass an extra argument in the max() function to get the keys with max value in a dictionary.

Syntax: max(iterable,key=d.get) where d denotes the name of the dictionary.

It returns the item with maximum value in the Iterable.

So with the help of the max() function and d.get argument we can easily find the key with max value in a dictionary.

d = {"a": 1, "b": 2, "c": 3,"d":4}
max_key = max(d, key=d.get)
print(max_key)

Output

d

Here we see that corresponding to key “d” we get max value so this function return d as the output.

There is a small problem with this method. Let see the problem and see the method to solve the problem.

Problem

Python max dictionary: The problem with this method is that if in the dictionary multiple keys have max value then this method only returns the key that occurs first in the dictionary. Let see this with the help of an example.

d = {"a": 1, "b": 2, "c":4,"d":4}
max_key = max(d, key=d.get)
print(max_key)

Output

c

In the dictionary, we see that the dictionary has max value 4 corresponds to key c and d still function only return c as the output because c comes first in the dictionary. So this is the main problem with this method.

So if there is a problem so solution also exists. As this problem occurs with all the methods so after study all the methods we can discuss the solution to the problem.

Method 2-Using max function() and operator

Maximum value in dictionary python: As we have already discussed max() function now we will discuss the operator module in python and how to use it in our program to get key with maximum value.

operator module

Max value in a dictionary python: The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x,y) is equivalent to the expression x+y.

Let see with an example how we can achieve our objective with the help of max and operator module.

import operator
d={"a":1,"b":2,"c":3,"d":4}
max_key = max(d.items(), key = operator.itemgetter(1))[0]
print(max_key)

Output

d

So here is an example of how with using the max() function and operator module we get a key with maximum value in the dictionary. Here also a similar problem arises that if we have multiple keys with max value so the function returns the only key with the first occurrence.

The solution to the above problem

Python get all keys in dictionary: In both the method we see that how we only get one key if we have multiple keys with max value. So let discuss the solution. We can be done this task with the help of a single iteration over the dictionary. As we get almost one key that corresponds to the max value in the dictionary. So we can take the help of the key to get max value. Now we can iterate over the dictionary and check the key having max value and store these keys in a list and then print the list. Let see this with the help of an example.

d = {"a": 1, "b": 2, "c":4,"d":4}

max_key = max(d, key=d.get)
val=d[max_key]
l=[]
for key in d:
    if(d[key]==4):
        l.append(key)
print(l)

Output

['c', 'd']

So here we see how we can easily print a list of keys having max value.

So these are the methods to get key with max value in a python dictionary.

One liner if else python – Python: if-else in One Line/Ternary Operator in Python

How to write an if-else statement in one line in python

One liner if else python: In this article, we will discuss how we can implement the if-else statement in python in a single line. This is also called the ternary operator. In python, the ternary operator doesn’t have syntax like that in c++ or java but working is the same. Let us see this concept with some examples.

Syntax: val1 if [expression] else val2

Explanation: If our if the statement becomes true then we get output as val1 otherwise we get output as val2.Let us see this with an example.

a=10
print(1 if a%2==0 else 0)
a=9
print(1 if a%2==0 else 0)

Output

1
0

Here we see that we get output 1 when our number is even else we get output as 0. When the condition evaluates to True, then the result of this one-liner if..else expression will be val1 in this case 1. Whereas, if the condition evaluates to False, then the result of this one-liner expression will be val2 in this case 0.

Here we use integer with our if-else statement. Let us see an example of how to deal with a string.

a=10
print("Number is even" if a%2==0 else "Number is odd")

Output

Number is even

Here we see that how we easily deal with string with this ternary operator or one-liner if-else statement. In a similar way, we can deal with different data types.

With the increase in the simplicity of code, we also have to take some precaution otherwise a situation may arise in which we understand the code in a different way while the code work in a different way. As different operator have different associativity and precedence which increase the responsibility of the programmer to use this operator in a correct way. Let us understand the concept with help of an example.

a=10 
b=5
print(a/b*3 if a%2==0 else 1)
print(a/(b*3 if a%2==0 else 1))

Output

6.0
0.6666666666666666

Here we see with change in one bracket our output differ but code seems to be similar.This confusion tend to be increase when we write big and complex code.Hence we have to use operator in a proper way.

Note: Conditional expressions have the lowest priority amongst all Python operations.

Nested if-else in one line

If else one liner python: We see that we can execute single if-else in a single line easily.Now we see how we can execute multiple if else statement in a single line with the help of an example.

a=10 
print("a is negative" if a<0 else "a is positive" if a>0 else "a is 0")

#above code is similar as
if(a<0):
    print("a is negative")
else:
    if(a>0):
        print("a is positive")
    else:
        print("a is 0")

Output

a is positive
a is positive

Both the code give a similar result. We see how we save 5-6 lines by using the ternary operator.

So in this article, we see how to use the if-else and nested if-else statement in one line and with that, we see how to use the operator effectively otherwise the result may differ.

C++ raise to power – C++ Program to Calculate Power of a Number

C++ Program to Calculate Power of a Number

C++ raise to power: In the previous article, we have discussed about C++ Program to Check Leap Year. Let us learn how to Calculate Power of a Number in C++ Program.

Method to calculate the power of a number in c++

C++ power of a number: In this article, we see different methods to calculate the power of numbers in c++. Here we take “a” as our number and “b” as the power. So here we see how can we find a raised to the power p or simply say a^b. Let see the different method to calculate the power of number.

Method 1-Using loop

How to raise something to a power in c++: In this method, we will see how we can calculate the power of a number by iterating through the loop. suppose we have to calculate 2 raised to the power 3 so we can run for loop 3 times and multiply number 3 times in itself and store it in a variable. For better understanding let write code for the program.

#include <iostream>
using namespace std;

int main() {
   int a=2,b=3,res=1,i;
   
   for(i=0;i<b;i++)
   {
       res=res*a;
   }
   cout<<a<<" raised to power "<<b<<" is "<<res;
    return 0;
}

Output

2 raised to power 3 is 8

Method 2-Using Recursion

Raise to power c++: We know that recursion is a method or procedure in which a method calls itself again and again. Let see how we can apply recursion here.

We can write 2^3 as 2*(2^2) and this as 4*(2). That’s how recursion work here. For better understanding let’s write code for this.

#include <iostream>
using namespace std;

int power(int a,int b)
{
    if(b==0)
    {
        return 1;
    }
    return a*power(a,b-1);
}
int main() {
   int a=2,b=3,res;
   res=power(a,b);
   cout<<a<<" raised to power "<<b<<" is "<<res;
    return 0;
}

Output

2 raised to power 3 is 8

Here we see that we calculate power function again and again. So this is how we use recursion to calculate power.

Method 3-Using inbuilt method pow()

How to raise a number to a power in c++: In c++ we have an inbuilt method pow() which contains two arguments a and b where a is the number and b is the power. This function returns a raise to the power b. Here we must remember that this function is contained in another library in c++ and not in iostream so instead of including iostream we can include bits/stdc++.h. Let write code for this.

#include <bits/stdc++.h>
using namespace std;

int main() {
   int a=2,b=3,res;
   res=pow(a,b);
   cout<<a<<" raised to power "<<b<<" is "<<res;
    return 0;
}

Output

2 raised to power 3 is 8

So these are the methods to calculate the power of numbers in c++.

Append/Add Row to Dataframe in Pandas – dataframe.append() | How to Insert Rows to Pandas Dataframe?

Append Add Row to Dataframe in Pandas

Insert row pandas: Worried about how to append or add rows to a dataframe in Pandas? Then, this tutorial will guide you completely on how to append rows to a dataframe in Pandas Python using the function dataframe.append() We have listed the various methods for appending rows to a dataframe. In this tutorial, we will discuss how to append or add rows to the dataframe in Pandas. Before going to the main concept let us discuss some basic concepts about pandas and Dataframes.

Pandas – Definition

Pandas append row from another dataframe: Pandas is a package in python that is used to analyze data in a very easy way. The reason why pandas are so famous is that it is very easy to use. But we can not directly use the pandas’ package in our program. To use this package first we have to import it.

Dataframe – Definition

Python add row to dataframe: Dataframe is a 2D data structure that store or represent the data in the 2D form or simply say in tabular form. The tabular form consists of rows, columns, and actual data. By using pandas we can manipulate the data as we want i.e we can see as many columns as we want or as many rows as we want. We can group the data or filter the data.

Let us understand both dataframe and pandas with an easy example

import pandas as pd
d={"Name":["Mayank","Raj","Rahul","Samar"],
   "Marks":[90,88,97,78]
  }
df=pd.DataFrame(d)
print(df)

Output

    Name  Marks
0  Mayank     90
1     Raj     88
2   Rahul     97
3   Samar     78

Here we see that first, we import our pandas package then we create a dictionary, and out of this dictionary, we create our dataframe. When we see our dataframe we see that it consists of rows and columns and data. There are many ways to create a dataframe like importing excel or CSV files or through a dictionary but this is not the main concern of this article.

Before understanding the concept of appending rows to a dataframe first we have to know a little bit about the append() method.

append() method

Append row to dataframe pandas: append() method is used to append rows of other dataframe at the end of the original or given dataframe. It returns a new dataframe object. If some columns are not presented in the original dataframe but presented in a new dataframe then-new column will also be added in the dataframe and data of that column will become NAN.
Syntax: DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=None)

Ways on Pandas append row to Dataframe

Method 1- How to Add dictionary as a row to dataframe

Pandas add row to dataframe: In this method, we see how we can append dictionaries as rows in pandas dataframe. It is a pretty simple way. We have to pass a dictionary in the append() method and our work is done. That dictionary is passed as an argument to other the parameter in the append method. Let us see this with an example.

Add dictionary as a row to dataframe in Pandas

d={"Name":["Mayank","Raj","Rahul","Samar"],
   "Marks":[90,88,97,78]
  }
df=pd.DataFrame(d)
print(df)
print("---------------")
new_d={"Name":"Gaurav",
      "Marks":76}
new_df=df.append(new_d,ignore_index=True)
print(new_df)

Output:

     Name  Marks
0  Mayank     90
1     Raj     88
2   Rahul     97
3   Samar     78
---------------
     Name  Marks
0  Mayank     90
1     Raj     88
2   Rahul     97
3   Samar     78
4  Gaurav     76
Explanation:
Add row to dataframe pandas: In this example, we see how we can append a dictionary in our original dataframe. By this method, our original dataframe will not affect that why we store the new Dataframe in a new variable so that we can analyze the changes.
Instead of assigning it to a new variable, we can assign it to the original dataframe in this case our original dataframe gets modify. It means that the append() method is not inplace.
Note: Passing ignore_index=True is necessary while passing dictionary or series otherwise a TypeError error will come.

Method 2 – Add Series as a row in the dataframe

Add row to dataframe python: This is another method to append rows in the dataframe. Let us see why this method is needed.

Add Series as a row in the dataframe in Pandas

d={"Name":["Mayank","Raj","Rahul","Samar"],
   "Marks":[90,88,97,78]
  }
df=pd.DataFrame(d)
print(df)
print("---------------")
new_d={"Name":["Gaurav","Vijay"],
      "Marks":[76,88]}
new_df=df.append(new_d,ignore_index=True)
print(new_df)

Output:

    Name  Marks
0  Mayank     90
1     Raj     88
2   Rahul     97
3   Samar     78
---------------
              Name     Marks
0           Mayank        90
1              Raj        88
2            Rahul        97
3            Samar        78
4  [Gaurav, Vijay]  [76, 88]

If we want to add multiple rows at one time and we try it using a dictionary then we get output like this then we get the output as shown above.

To solve this issue we use series. Let us understand what series means.

Series

Append row to dataframe: Series is a 1-D array that stores a single column or row of data in a dataframe.

syntax: pandas.Series( data, index, dtype, copy)

series=pd.Series(['Ajay','Vijay'])
print(series)
print(type(series))

Output

0     Ajay
1    Vijay
dtype: object
<class 'pandas.core.series.Series'>

That is how we can create a series in pandas. Now we see how we can append series in pandas dataframe. It is similar like as we pass our dictionary. We can simply pass series as an argument in the append() function. Let see this with an example.

d={"Name":["Mayank","Raj","Rahul","Samar"],
   "Marks":[90,88,97,78]
  }
df=pd.DataFrame(d)
print(df)
print("---------------")
series=[pd.Series(['Gaurav',88], index=df.columns ) ,
        pd.Series(['Vijay', 99], index=df.columns )]
new_df=df.append(series,ignore_index=True)
print(new_df)

Output:

     Name  Marks
0  Mayank     90
1     Raj     88
2   Rahul     97
3   Samar     78
---------------
     Name  Marks
0  Mayank     90
1     Raj     88
2   Rahul     97
3   Samar     78
4  Gaurav     88
5   Vijay     99

We see that by this method we solve the problem to add multiple rows at a time that we face in the dictionary.

Method 3 – How to Add row from one dataframe to another dataframe

Pandas add rows: To understand this method first we have to understand about concepts of loc.

loc[ ]

It is used to access groups of rows and columns by values. Let us understand this concept with help of an example.

students = [ ('Mayank',98) ,
             ('Raj', 75) ,
             ('Rahul', 87) ,
             ('Samar', 78)]
df = pd.DataFrame(  students, 
                    columns = ['Name' , 'Marks'],
                    index=['a', 'b', 'c' , 'd']) 
print(df)
print("------------------")
# If we want only row 'c' and all columns
print(df.loc[['c'],:])
print("------------------")
# If we want only row 'c' and only column 'Name'
print(df.loc['c']['Name'])
print("------------------")
# If we want only row 'c' and 'd' and all columns
print(df.loc[['c','d'],:])
print("------------------")
# If we want only row 'c' and 'd' and only column 'Name'
print(df.loc[['c','d'],['Name']])
print("------------------")

Output:

     Name  Marks
a  Mayank     98
b     Raj     75
c   Rahul     87
d   Samar     78
------------------
    Name  Marks
c  Rahul     87
------------------
Rahul
------------------
    Name  Marks
c  Rahul     87
d  Samar     78
------------------
    Name
c  Rahul
d  Samar
------------------

This example is very helpful to understand how loc works in pandas.

Now it can be very easy to understand how we can add rows of one dataframe to another dataframe. Let us see this with an example.

students1 = [ ('Mayank',98) ,
             ('Raj', 75) ,
             ('Rahul', 87) ,
             ('Samar', 78)]
df1 = pd.DataFrame(  students, 
                    columns = ['Name' , 'Marks'],
                    index=['a', 'b', 'c' , 'd']) 
print(df1)
print("------------------")
students2 = [ ('Vijay',94) ,
             ('Sunil', 76),
             ('Sanjay', 80)
            ]
df2= pd.DataFrame(  students2, 
                    columns = ['Name' , 'Marks'],
                    index=['a', 'b','c']) 
print(df2)

print("------------------")
new_df=df1.append(df2.loc[['a','c'],:],ignore_index=True)
print(new_df)

Output:

     Name  Marks
a  Mayank     98
b     Raj     75
c   Rahul     87
d   Samar     78
------------------
     Name  Marks
a   Vijay     94
b   Sunil     76
c  Sanjay     80
------------------
     Name  Marks
0  Mayank     98
1     Raj     75
2   Rahul     87
3   Samar     78
4   Vijay     94
5  Sanjay     80

In this example, we see how we easily append rows ‘a’ and ‘c’ of df2 in df1.

Method 4 – How to Add a row in the dataframe at index position using iloc[]

iloc[]

Typeerror: can only append a series if ignore_index=true or if the series has a name: iloc[] in pandas allows us to retrieve a particular value belonging to a row and column using the index values assigned to it. IT will raise Index errors if a requested indexer is out-of-bounds.

students1 = [ ('Mayank',98) ,
             ('Raj', 75) ,
             ('Rahul', 87) ,
             ('Samar', 78)]
df1 = pd.DataFrame(  students, 
                    columns = ['Name' , 'Marks'],
                    index=['a', 'b', 'c' , 'd']) 
print(df1.iloc[0])

Output

Name     Mayank
Marks        98
Name: a, dtype: object

This example shows how we can access any row using an index.

Note: We use the index in iloc and not the column name.

Now let us see how we can append row in dataframe using iloc

students1 = [ ('Mayank',98) ,
('Raj', 75) ,
('Rahul', 87) ,
('Samar', 78)]
df1 = pd.DataFrame( students, 
columns = ['Name' , 'Marks'],
index=['a', 'b', 'c' , 'd']) 
print("Original dataframe")
print(df1)
print("------------------")
df1.iloc[2] = ['Vijay', 80]
print("New dataframe")
print(df1)

Output:

Original dataframe
     Name  Marks
a  Mayank     98
b     Raj     75
c   Rahul     87
d   Samar     78
------------------
New dataframe
     Name  Marks
a  Mayank     98
b     Raj     75
c   Vijay     80
d   Samar     78

This example shows how we add a column in the dataframe at a specific index using iloc.

So these are the methods to add or append rows in the dataframe.

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 – Add Contents to a Dataframe

C++ get all files in directory – C++ Program to Get the List of all Files in a Given Directory and its Sub-Directories

C++ Program to Get the List of all Files in a Given Directory and its Sub-Directories

C++ get all files in directory: In the previous article, we have discussed C++ Program to Check Whether a Character is an Alphabet or Not. In this article, we will see C++ Program to Get the List of all Files in a Given Directory and its Sub-Directories.

Method to get the list of all files in a given directory and its sub-directories

C++ get list of files in directory: In this article, we discuss how can we get the list of all files in a given directory and its sub-directories. The method that we discuss is given below:

Let’s first understand what we actually going to do in this article. Suppose there is a path p=”dir/file1/file2″. So we have to list all the files in this path. In a path, there may be multiple directories and in these directories, there may be multiple files. So we have to return or print the list of all the files. So now let’s discuss the method.

Method 1:-Using recursive_directory_iterator

C++ list files in directory: First, we discuss what a recursive_directory_iterator is. C++17 Filesystem Library provides a recursive iterator for the recursive iteration over a directory. recursive_directory_iterator is a LegacyInputIterator that iterates over the directory_entry elements of a directory, and, recursively, over the entries of all subdirectories. The iteration order is unspecified, except that each directory entry is visited only once. Now let’s write the code of how to use recursive_directory_iterator to get the list of all files in a given directory and its sub-directories.

#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
 
int main()
{
    fs::current_path(fs::temp_directory_path());
    fs::create_directories("dir/file1/file2");
    std::ofstream("dir/file1.txt");
    fs::create_symlink("file1", "dir/file2");
    for(auto& p: fs::recursive_directory_iterator("dir"))
        std::cout << p.path() << '\n';
    fs::remove_all("dir");
}

Output

"dir/file2"
"dir/file1.txt"
"dir/file1"
"dir/file1/file2"

So here we see we get the list of all the files in the directory and sub_directories.

So this is the method to get the list of all the files in the directory and sub_directories in c++.

The popular Examples of C++ Code are programs to print Hello World or Welcome Note, addition of numbers, finding prime number and so on. Get the coding logic and ways to write and execute those programs.

Pandas drop row with nan – Pandas: Drop Rows With NaN/Missing Values in any or Selected Columns of Dataframe

Pandas Drop Rows With NaNMissing Values in any or Selected Columns of Dataframe

Pandas drop row with nan: Pandas provide several data structures and operations to manipulate data and time series. There might be instances in which some data can go missing and pandas use two values to denote the missing data namely None, NaN. You will come across what does None and Nan indicate. In this tutorial we will discuss the dropna() function, why is it necessary to remove rows which contain missing values or NaN, and different methods to drop rows with NaN or Missing values in any or selected column in the dataframe.

dropna() function

Pandas drop nan column: The dropna() function is used to analyze and drop rows or columns having NaN or missing values in different ways.

syntax:  DataFrameName.dropna(axis, how, thresh, subset, inplace)

Parameters:

1) axis: If the axis is 0 rows with missing or NaN values will be dropped else if axis=1 columns with NaN or missing values will be dropped.

2) how: how to take a string as a parameter ‘any’ or ‘all’.  ‘any’ is used if any NaN value is present otherwise ‘all’ is used if all values are NaN.

3) thresh: It tells the minimum amount of NaN values that is to be dropped.

4) inplace: If inplace is true chance will be made in the existing dataset otherwise changes will be made in different datasets.

The Necessity to remove NaN or Missing values

Delete rows with nan pandas: NaN stands for Not a Number. It is used to signify whether a particular cell contains any data or not. When we work on different datasets we found that there are some cells that may have NaN or missing values. If we work on that type of dataset then the chances are high that we do not get an accurate result. Hence while working on any dataset we check whether our datasets contain any missing values or not. If it contains NaN values we will remove it so as to get results with more accuracy.

How to drop rows of Pandas DataFrame whose value in a certain column is NaN or a Missing Value?

Drop rows with nan pandas: There are different methods to drop rows of Pandas Dataframe whose value is missing or Nan. All 4 methods are explained with enough examples so that you can better understand the concept and apply the conceptual knowledge to other programs on your own.

Method 1: Drop Rows with missing value / NaN in any column

Pandas remove rows with nan: In this method, we will see how to drop rows with missing or NaN values in any column. As we know in all our methods dropna() function is going to be used hence we have to play with parameters. By default value of the axis is 0 and how is ‘any’ hence dropna() function without any parameter will going to be used to drop rows with missing or NaN values in any column. Let see this with the help of an example.

import pandas as pd
import numpy as np
students = [('Raj', 24, 'Mumbai', 95) ,
            ('Rahul', 21, 'Delhi' , 97) ,
            ('Aadi', 22, np.NaN, 81) ,
            ('Abhay', np.NaN,'Rajasthan' , np.NaN) ,
            ('Ajjet', 21, 'Delhi' , 74)]
# Create a DataFrame object
df = pd.DataFrame(  students, 
                    columns=['Name', 'Age', 'City', 'Marks'])
print("Original Dataframe\n")
print(df,'\n')
new_df=df.dropna()
print("New Dataframe\n")
print(new_df)

How to Drop Rows with missing valueNaN in any column of Pandas Dataframe

Output

Original Dataframe

    Name   Age       City  Marks
0    Raj  24.0     Mumbai   95.0
1  Rahul  21.0      Delhi   97.0
2   Aadi  22.0        NaN   81.0
3  Abhay   NaN  Rajasthan    NaN
4  Ajjet  21.0      Delhi   74.0 

New Dataframe

    Name   Age    City  Marks
0    Raj  24.0  Mumbai   95.0
1  Rahul  21.0   Delhi   97.0
4  Ajjet  21.0   Delhi   74.0

Here we see that we get only those rows that don’t have any NaN or missing value.

Method 2: Drop Rows in dataframe which has all values as NaN

Pandas drop rows with nan in column: In this method, we have to drop only those rows in which all the values are NaN or missing. Hence we have to only pass how as an argument with value ‘all’ and all the parameters work with their default values. Let see this with an example.

import pandas as pd
import numpy as np
students = [('Raj', 24, 'Mumbai', 95) ,
            ('Rahul', 21, 'Delhi' , 97) ,
            ('Aadi', 22, np.NaN, 81) ,
            ('Abhay', np.NaN,'Rajasthan' , np.NaN) ,
            ('Ajjet', 21, 'Delhi' , 74),
            (np.NaN,np.NaN,np.NaN,np.NaN),
            ('Aman',np.NaN,np.NaN,76)]
# Create a DataFrame object
df = pd.DataFrame(  students, 
                    columns=['Name', 'Age', 'City', 'Marks'])
print("Original Dataframe\n")
print(df,'\n')
new_df=df.dropna(how='all')
print("New Dataframe\n")
print(new_df)

 

How to Drop Rows in dataframe which has all values as NaN in Pandas Dataframe

Output

Original Dataframe

    Name   Age       City  Marks
0    Raj  24.0     Mumbai   95.0
1  Rahul  21.0      Delhi   97.0
2   Aadi  22.0        NaN   81.0
3  Abhay   NaN  Rajasthan    NaN
4  Ajjet  21.0      Delhi   74.0
5    NaN   NaN        NaN    NaN
6   Aman   NaN        NaN   76.0 

New Dataframe

    Name   Age       City  Marks
0    Raj  24.0     Mumbai   95.0
1  Rahul  21.0      Delhi   97.0
2   Aadi  22.0        NaN   81.0
3  Abhay   NaN  Rajasthan    NaN
4  Ajjet  21.0      Delhi   74.0
6   Aman   NaN        NaN   76.0

Here we see that row 5 is dropped because it has all the values as NaN.

Method 3: Drop Rows with any missing value in selected columns only

Remove nan rows pandas: In this method, we see how to drop rows with any of the NaN values in the selected column only. Here also axis and how to take default value but we have to give a list of columns in the subset in which we want to perform our operation. Let see this with the help of an example.

import pandas as pd
import numpy as np
students = [('Raj', 24, 'Mumbai', 95) ,
            ('Rahul', 21, 'Delhi' , 97) ,
            ('Aadi', 22, np.NaN, 81) ,
            ('Abhay', np.NaN,'Rajasthan' , np.NaN) ,
            ('Ajjet', 21, 'Delhi' , 74),
            (np.NaN,np.NaN,np.NaN,np.NaN),
            ('Aman',np.NaN,np.NaN,76)]
# Create a DataFrame object
df = pd.DataFrame(  students, 
                    columns=['Name', 'Age', 'City', 'Marks'])
print("Original Dataframe\n")
print(df,'\n')
new_df=df.dropna(subset=['Name', 'Age'])
print("New Dataframe\n")
print(new_df)

How to Drop Rows with any missing value in selected columns only in Pandas Dataframe

Output

Original Dataframe

    Name   Age       City  Marks
0    Raj  24.0     Mumbai   95.0
1  Rahul  21.0      Delhi   97.0
2   Aadi  22.0        NaN   81.0
3  Abhay   NaN  Rajasthan    NaN
4  Ajjet  21.0      Delhi   74.0
5    NaN   NaN        NaN    NaN
6   Aman   NaN        NaN   76.0 

New Dataframe

    Name   Age    City  Marks
0    Raj  24.0  Mumbai   95.0
1  Rahul  21.0   Delhi   97.0
2   Aadi  22.0     NaN   81.0
4  Ajjet  21.0   Delhi   74.0

Here we see in rows 3,5 and 6 columns ‘Name’ and ‘Age’ has NaN or missing values so these columns are dropped.

Method 4: Drop Rows with missing values or NaN in all the selected columns

Pandas remove nan rows: In this method we see how to drop rows that have all the values as NaN or missing values in a select column i.e if we select two columns ‘A’ and ‘B’ then both columns must have missing values. Here we have to pass a list of columns in the subset and ‘all’ in how. Let see this with the help of an example.

import pandas as pd
import numpy as np
students = [('Raj', 24, 'Mumbai', 95) ,
            ('Rahul', 21, 'Delhi' , 97) ,
            ('Aadi', 22, np.NaN, 81) ,
            ('Abhay', np.NaN,'Rajasthan' , np.NaN) ,
            ('Ajjet', 21, 'Delhi' , 74),
            (np.NaN,np.NaN,np.NaN,np.NaN),
            ('Aman',np.NaN,np.NaN,76)]
# Create a DataFrame object
df = pd.DataFrame(  students, 
                    columns=['Name', 'Age', 'City', 'Marks'])
print("Original Dataframe\n")
print(df,'\n')
new_df=df.dropna(how='all',subset=['Name', 'Age'])
print("New Dataframe\n")
print(new_df)

How to Drop Rows with missing values or NaN in all the selected columns in Pandas Dataframe

Output

Original Dataframe

    Name   Age       City  Marks
0    Raj  24.0     Mumbai   95.0
1  Rahul  21.0      Delhi   97.0
2   Aadi  22.0        NaN   81.0
3  Abhay   NaN  Rajasthan    NaN
4  Ajjet  21.0      Delhi   74.0
5    NaN   NaN        NaN    NaN
6   Aman   NaN        NaN   76.0 

New Dataframe

    Name   Age       City  Marks
0    Raj  24.0     Mumbai   95.0
1  Rahul  21.0      Delhi   97.0
2   Aadi  22.0        NaN   81.0
3  Abhay   NaN  Rajasthan    NaN
4  Ajjet  21.0      Delhi   74.0
6   Aman   NaN        NaN   76.0

Here we see that only row 7 has NaN value in both the columns hence it is dropped, while row 3 and row 6 have NaN value only in the age column hence it is not dropped.

So these are the methods to drop rows having all values as NaN or selected value as NaN.

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 Pandas – Remove Contents from a Dataframe

Numpy unique – Python: Find Unique Values in a Numpy Array With Frequency and Indices

Methods to find unique values in a numpy array with frequency and indices

Numpy get unique values: In this article, we will discuss how to find unique values, rows, and columns in a 1D & 2D Numpy array. Before going to the methods first we see numpy.unique() method because this method is going to be used.

numpy.unique() method

Numpy unique: numpy.unique() method help us to get the unique() values from given array.

syntax:numpy.unique(array, return_index=False, return_inverse=False, return_counts=False, axis=None)

Parameters

  1. array-Here we have to pass our array from which we want to get unique value.
  2. return_index- If this parameter is true then it will return the array of the index of the first occurrence of each unique value. By default it is false.
  3. return_counts-If this parameter is true then it will return the array of the count of the occurrence of each unique value. By default it is false.
  4. axis- It is used in the case of nd array, not in 1d array. axis=1 means we have to do operation column-wise and axis=0 means we have to do operation row-wise.

Now we will see different methods to find unique value with their indices and frequencies in a numpy array.

case 1-When our array is 1-D

  • Method 1-Find unique value from the array

Numpy unique values: As we only need unique values and not their frequencies and indices hence we simply pass our numpy array in the unique() method because the default value of other parameters is false so we don’t need to change them. Let see this with the help of an example.

import numpy as np
arr = np.array([1, 1, 2, 3, 4, 5, 6, 7, 2, 3, 1, 4, 7])
unique_values=np.unique(arr)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)

Output

Original array is
[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]
  • Method 2-Find unique value from the array along with their indices

Numpy frequency count: In this method, as we want to get unique values along with their indices hence we make the return_index parameter true and pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([1, 1, 2, 3, 4, 5, 6, 7, 2, 3, 1, 4, 7])
unique_values,index=np.unique(arr,return_index=True)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)
print("First index of unique values are:")
print(index)

Output

Original array is
[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]
First index of unique values are:
[0 2 3 4 5 6 7]
  • Method 3-Find unique value from the array along with their frequencies

Numpy count unique: In this method, as we want to get unique values along with their frequencies hence we make the return_counts parameter true and pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([1, 1, 2, 3, 4, 5, 6, 7, 2, 3, 1, 4, 7])
unique_values,count=np.unique(arr,return_counts=True)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)
print("Count of unique values are:")
for i in range(0,len(unique_values)):
  print("count of ",unique_values[i]," is ",count[i])

Output

Original array is
[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]
Count of unique values are:
count of  1  is  3
count of  2  is  2
count of  3  is  2
count of  4  is  2
count of  5  is  1
count of  6  is  1
count of  7  is  2

Case 2: When our array is 2-D

  • Method 1-Find unique value from the array

Numpy unique: Here we simply pass our array and all the parameter remain the same. Here we don’t make any changes because we want to work on both rows and columns. Let see this with the help of an example.

import numpy as np
arr = np.array([[1, 1, 2,1] ,[ 3, 1, 2,1] , [ 6, 1, 2, 1],  [1, 1, 2, 1]])
unique_values=np.unique(arr)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)

Output

Original array is
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]
 [1 1 2 1]]
------------------
Unique values are
[1 2 3 6]

Method 2-Get unique rows

Numpy unique: As here want to want to work only on rows so here we will make axis=0 and simply pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([[1, 1, 2,1] ,[ 3, 1, 2,1] , [ 6, 1, 2, 1],  [1, 1, 2, 1]])
unique_values=np.unique(arr,axis=0)
print("Original array is")
print(arr)
print("------------------")
print("Unique rows are")
print(unique_values)

Output

Original array is
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]
 [1 1 2 1]]
------------------
Unique rows are
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]]

Method 3-Get unique columns

As here want to want to work only on columns so here we will make axis=1 and simply pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([[1, 1, 2,1] ,[ 3, 1, 2,1] , [ 6, 1, 2, 1],  [1, 1, 2, 1]])
unique_values=np.unique(arr,axis=1)
print("Original array is")
print(arr)
print("------------------")
print("Unique columns are")
print(unique_values)

Output

Original array is
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]
 [1 1 2 1]]
------------------
Unique columns are
[[1 1 2]
 [1 3 2]
 [1 6 2]
 [1 1 2]]

so these are the methods to find unique values in a numpy array with frequency and indices.