Categories
python

Slicing in python

In this post, let us discuss slicing in python with examples.

How Indexing works ?

For your reminder, Indexing starts from zero.
In the below example, a[0] & a[1] help us to get the element present in the zeroth and first index position

Program

print("creating a new list")
a=[9,8,7,6,5,4,3,2,1]
print("printing the elements of the list")
print(a)
print("printing the first element")
print(a[0])
print("printing the second element")
print(a[1])

Output

creating a new list
printing the elements of the list
[9, 8, 7, 6, 5, 4, 3, 2, 1]
printing the first element
9
printing the second element
8

What is Slicing ?

Slicing in python helps us in getting the specific range of elements based on their position from the collection.

Here comes the syntax of slicing which lists the range from index position one to two. It neglects the element present in the third index.
Below is the official document
https://docs.python.org/2.3/whatsnew/section-slices.html

Slicing in Python

Program

a=[9,8,7,6,5,4,3,2,1]
print("printing the first 3 elements of a list")
print(a[0:3])
print("other way to print first 3 elements of a list")
print(a[:3])

Output

printing the first 3 elements of a list
[9, 8, 7]
other way to print first 3 elements of a list
[9, 8, 7]

Positive and Negative indexing in slicing

There are two types of indexing available :

1) Positive Indexing
2) Negative Indexing

Positive Indexing

Program

a=[9,8,7,6,5,4,3,2,1]
print("printing second and third element in a list")
print(a[1:3])

Output

printing second and third element in a list
[8, 7]

Negative indexing

Program

a=[9,8,7,6,5,4,3,2,1]
print("printing the last element")
print(a[-1])
print("printing last three elements in a list")
print(a[-3:])
print("printing from second element till second last element")
print(a[1:-1])

Output

printing the last element
1
printing last three elements in a list
[3, 2, 1]
printing from second element till second last element
[8, 7, 6, 5, 4, 3]

Interview Q&A

How to reverse the elements present in a list?

Program

a=[9,8,7,6,5,4,3,2,1]
print("Reversing the elements")
print(a[::-1])

Output

Reversing the elements
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Create dataframe in python

Categories
ag-grid Angular

ag grid angular examples

In this post, we will see ag grid angular examples. ag grid is one of the most commonly used grid in modern web applications. It is easy to integrate with java script, angular. react ,vue.js.

It is available in both community & enterprise edition
https://www.ag-grid.com/documentation/

In this post we will learn to integrate the ag grid with angular. We are consider that you have a angular project already

Install ag grid in angular project

Run below commands to install ag grid in the angular project, Below will install the ag grid community version to your application

npm install --save ag-grid-community ag-grid-angular
npm install

app.module.ts

Add ag-grid module in app.module.ts as like below

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { AgGridModule } from 'ag-grid-angular';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    AgGridModule.withComponents([])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Ag-grid Styling

ag-grid is coming with multiple styling and themes you have to add below code in the src/style.css file

@import "../node_modules/ag-grid-community/dist/styles/ag-grid.css";
@import "../node_modules/ag-grid-community/dist/styles/ag-theme-alpine.css";

Below are the providing themes in ag grid

  • ag-theme-alpine
    • @import “../node_modules/ag-grid-community/dist/styles/ag-theme-alpine.css”;
  • ag-theme-alpine-dark
    • @import “../node_modules/ag-grid-community/dist/styles/ag-theme-alpine-dark.css”;
  • ag-theme-balham
    • @import “../node_modules/ag-grid-community/dist/styles/ag-theme-balham.css”;
  • ag-theme-balham-dark
    • @import “../node_modules/ag-grid-community/dist/styles/ag-theme-balham-dark.css”
  • ag-theme-material
    • @import “../node_modules/ag-grid-community/dist/styles/ag-theme-material.css”

Adding grid in angular

We have to add column definition and row data in the component.ts file, Below is the snippet of app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ag-custom';


  columnDefs = [
    { headerName: "Make", field: "make" ,resizable: true,filter: true  },
    { headerName: "Model", field: "model",resizable: true ,filter: true  },
    { headerName: "Price", field: "price",resizable: true ,filter: true  }
  ];

  rowData = [
    { make: "Toyota", model: "Celica", price: 35000 },
    { make: "Ford", model: "Mondeo", price: 32000 },
    { make: "Porsche", model: "Boxter", price: 72000 }
  ];

}

In the app.component.html file add the below snippet

<div>
  <ag-grid-angular style="width: 100%; height: 500px;" class="ag-theme-alpine" [rowData]="rowData"
    [columnDefs]="columnDefs">
  </ag-grid-angular>
</div>

Output

Github

https://github.com/rkumar9090/ag-grid

Categories
Angular

Interceptor in angular

Interceptor in angular will intercept each http request and response also error

Syntax

interface HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
}

CLI command to create interceptor

Once you created the angular application, naviagate to root folder and execute below command to create interceptor

ng g interceptor (name)

Now a class will be created as like below

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class MyappintercepInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request);
  }
}

The class should implement HttpInterceptor interface. The method intercept will handle the request and response

You should add this interceptor in your app module.ts file in the provider section as like below

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AgGridModule } from 'ag-grid-angular';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyappintercepInterceptor } from './myappintercep.interceptor';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AgGridModule.withComponents([]),
    AppRoutingModule
  ],
  providers: [{provide: HTTP_INTERCEPTORS, useClass: MyappintercepInterceptor, multi: true }  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

You have to clone the request to add token in the http request headers as like below

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class MyappintercepInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {

    request = request.clone({
      setHeaders: {
        'apptoken': 'SYSTEM'
      }
    });
    
    return next.handle(request);
  }
}

Categories
pandas python

create dataframe in python using pandas

In this post, we will learn about create dataframe in python using pandas. There are multiple ways to create dataframe in python

DataFrame

Dataframe is one of the data types in python as like string, int. It will look like a table.

It consists of rows and columns. We can say that it is a two-dimensional array.

Here we are using pandas to create the data frame. Pandas is a fast and powerful open-source package.
For More details refer the doc below
https://pandas.pydata.org/

Installing Pandas Libraries using pip

pip install pandas

Installing Pandas libraries using conda

conda install pandas

In order to use pandas, we should install a pandas package on our machine.
Open the terminal/Command prompt and run any one of the above commands
Once you installed we need to import using the import command below

import pandas as pd

Here I am going to create a data frame with avengers details as like below image

Below are the multiple ways to create dataframe in python using pandas.

  • Create data frame from list
  • Create data frame using dictionary
  • Create data frame from csv file
  • Load Mysql table as dataframe using pandas
  • Load Mongodb collection as dataframe
1. Create data frame from list
import pandas as pd

avengers_column_details = ['ID', 'Character Name', 'Real Name']
avengers_data = [[1, 'Hulk', 'Mark Ruffalo'], [2, 'Thor', 'Chris Hemsworth'], [3, 'Black Widow', 'Scarlett Johansson'], [4, 'Iron Man', 'Robert Downey Jr'],[5, 'Captain America', 'Chris Evans']]

df_avengers_details = pd.DataFrame(avengers_data, columns=avengers_column_details)
print("Created Dataframe using List")
print(df_avengers_details)
Output using list
 Created Dataframe using List
    ID   Character Name           Real Name
 0   1             Hulk        Mark Ruffalo
 1   2             Thor     Chris Hemsworth
 2   3      Black Widow  Scarlett Johansson
 3   4         Iron Man    Robert Downey Jr
 4   5  Captain America         Chris Evans

In the above example, we have created a data frame using the list.

2. Create data frame using dictionary
import pandas as pd

dict_avengers_data={"ID": [1, 2, 3, 4, 5],
                    "Character Name": ['Hulk', 'Thor', 'Black Widow', 'Iron Man', 'Captain America'],
                    "Real Name": ['Mark Ruffalo', 'Chris Hemsworth', 'Scarlett Johansson', 'Robert Downey Jr', 'Chris Evans']}
df_avengers_dict = pd.DataFrame(dict_avengers_data)
print("Created Dataframe using dict")
print(df_avengers_dict)
Output
Created Dataframe using dict
    ID   Character Name           Real Name
 0   1             Hulk        Mark Ruffalo
 1   2             Thor     Chris Hemsworth
 2   3      Black Widow  Scarlett Johansson
 3   4         Iron Man    Robert Downey Jr
 4   5  Captain America         Chris Evans

Here we are created a data frame using the dictionary. Printed the output.

3. Create data frame from csv file

In the below code, we are importing a CSV file as a data frame with the help of pandas library

import pandas as pd

df_avenger_data_csv = pd.read_csv("D://avenger_details.csv")
print("Created Dataframe using csv file")
print(df_avenger_data_csv)
print("\n")
Output
Created Dataframe using csv file
    ID   Character Name           Real Name
 0   1             Hulk        Mark Ruffalo
 1   2             Thor     Chris Hemsworth
 2   3      Black Widow  Scarlett Johansson
 3   4         Iron Man    Robert Downey Jr
 4   5  Captain America         Chris Evans
4. Load Mysql table as dataframe using pandas

To load the MySQL table data as a data frame we need a MySQL connector library. you can install using the below command

 pip install mysql-connector-python

Once you installed the MySQL connector in your system. you need to create the MySQL connection object and need to pass the connection object and query to the pandas as below

import pandas as pd
import mysql.connector

mysql_connection = mysql.connector.connect(host="localhost", user="root", password="password", database="avengers")
df = pd.read_sql("select * from avengersdetails", mysql_connection)
print("Created Dataframe from mysql table")
print(df)
mysql_connection.close()
Output
Created Dataframe from mysql table
    ID    CharacterName            RealName
 0   1             Hulk        Mark Ruffalo
 1   2             Thor     Chris Hemsworth
 2   3      Black Widow  Scarlett Johansson
 3   4         Iron Man    Robert Downey Jr
 4   5  Captain America         Chris Evans
5. Load Mongodb collection as dataframe

To load the MongoDB collection data as a data frame we need pymongo library. you can install using the below command

pip install pymongo

Once you installed the pymongo in your system. you need to create the MongoDB connection object. After that, you need to convert MongoDB to pandas data frame

For connecting python with MongoDB refer this
https://beginnersbug.com/python-with-mongodb/

import pandas as pd
import pymongo

mongodb_connection = pymongo.MongoClient("mongodb://localhost:27017/")
mongodb_db = mongodb_connection["avengers"]
mongodb_avengers = mongodb_db["avengersdetails"].find()
df_mongodb_avengers = pd.DataFrame(list(mongodb_avengers))
print("Created Dataframe from mongodb collections")
print(df_mongodb_avengers)
Output
Created Dataframe from mongodb collections
                         _id ID   Character Name           Real Name
 0  5fd0e603549a851a24a48c36  1             Hulk        Mark Ruffalo
 1  5fd0e603549a851a24a48c37  2             Thor     Chris Hemsworth
 2  5fd0e603549a851a24a48c38  3      Black Widow  Scarlett Johansson
 3  5fd0e603549a851a24a48c39  4         Iron Man    Robert Downey Jr
 4  5fd0e603549a851a24a48c3a  5  Captain America         Chris Evans
Related Articles
Categories
mysql

exists and not exists in MySQL

In this post, let us learn about the options exists and not exists in MySQL.

To understand this better, we will make use of the following two tables in the post.

Both tables are having the same columns with common and uncommon records.

mysql> select * from Employee_details;
+----------+--------+--------+
| Dep_name | Emp_id | Salary |
+----------+--------+--------+
| Computer |    564 |   1400 |
| Computer |    123 |   2500 |
| Computer |    943 |   3200 |
| History  |    987 |   3450 |
| Economy  |    456 |   4500 |
| Economy  |    678 |   6700 |
| Economy  |    789 |   7200 |
| Computer |    324 |   2500 |
+----------+--------+--------+
8 rows in set (0.00 sec)
mysql> select * from Company;
+----------+--------+--------+
| Dep_name | Emp_id | Salary |
+----------+--------+--------+
| Computer |    564 |   1400 |
| Computer |    943 |   3200 |
| History  |    987 |   3450 |
| Economy  |    456 |   4500 |
| History  |    987 |   3450 |
+----------+--------+--------+
5 rows in set (0.00 sec)
How to use?

The below option filters data from the first table if it is not present in the subquery.

The following records are present in the Employee details and not in the Company.

mysql> select * from Employee_details a where not exists (select * from Company
b where a.Emp_id =b.Emp_id );
+----------+--------+--------+
| Dep_name | Emp_id | Salary |
+----------+--------+--------+
| Computer |    123 |   2500 |
| Economy  |    678 |   6700 |
| Economy  |    789 |   7200 |
| Computer |    324 |   2500 |
+----------+--------+--------+
4 rows in set (0.00 sec)

Exists option filters the data from the first table if it presents in the subquery.

The following records present in both tables Employee_details and Company.

mysql> select * from Employee_details a where exists (select * from Company b wh
ere a.Emp_id =b.Emp_id );
+----------+--------+--------+
| Dep_name | Emp_id | Salary |
+----------+--------+--------+
| Computer |    564 |   1400 |
| Computer |    943 |   3200 |
| History  |    987 |   3450 |
| Economy  |    456 |   4500 |
+----------+--------+--------+
4 rows in set (0.00 sec)
Reference

https://dev.mysql.com/doc/refman/8.0/en/exists-and-not-exists-subqueries.html

Related Articles

https://beginnersbug.com/subtracting-dataframes-in-pyspark/

Categories
pyspark

Transformation and action in pyspark

In this post, let us learn about transformation and action in pyspark.

Transformation

Transformation is one of the operations available in pyspark.

This helps in creating a new RDD from the existing RDD.

Types of transformation

Narrow transformation :

map,filter,flatmap,distinct,sample,union,intersection,join,coalesce,repartition,pipe,cartesian

Wide transformation :

groupByKey,reduceByKey,aggregateByKey,sortByKey

What is action ?

On applying the transformation, DAG(Directed Acyclic Graph)  is usually created. And this develops on further application of some other operations.

But the operations will execute only if action is called upon.

Types of action

reduce,collect,take,head,count,first,saveAsObjectFile,countByKey,foreach,saveAsSequenceFile,saveAsTextFile,takeOrdered,takeSample

Sample program

The following program helps us to filter elements based on some conditions.

But the steps execute only at the collect function. 

from pyspark.sql import SparkSession
from pyspark import SparkContext
sc = SparkContext()
spark = SparkSession(sc)
rdd1=sc.parallelize([1,2,3,4])
rdd1_first=rdd1.filter(lambda x : x<3)
rdd1_first.collect()
[1, 2]

https://beginnersbug.com/rank-and-dense-rank-in-pyspark-dataframe/

https://beginnersbug.com/window-function-in-pyspark-with-example/

Categories
pyspark

Difference between map and flatmap in pyspark

In this post, let us learn about the difference between map and flatmap in pyspark.

What is the difference between Map and Flatmap?

Map and Flatmap are the transformation operations available in pyspark.

The map takes one input element from the RDD and results with one output element. The number of input elements will be equal to the number of output elements.

In the case of Flatmap transformation, the number of elements will not be equal. That is the difference between the two.

Let the below example clarify it clearly.

How to create an RDD ?

With the below part of the code, an RDD is created using parallelize method and its value is viewed.

Let us discuss the topic below with the created RDD.

# Creating RDD using parallelize method
rdd1=sc.parallelize([1,2,3,4])
rdd1.collect()

The RDD contains the following 4 elements.

[1, 2, 3, 4]
How to apply map transformation ?
# Applying map transformation
rdd1_map=rdd1.map(lambda x : x**2)
# Viewing the result
rdd1_map.collect()

In the below result , the output elements are the square of the input elements. And also the count is equal.

[1, 4, 9, 16]
How to apply flatMap transformation ?
# Applying flatmap transformation
rdd1_second=rdd1.flatMap(lambda x : (x**1,x**2))
# Viewing the result
rdd1_second.collect()

In the below result, we are not finding an equal number of elements as map transformation.

[1, 1, 2, 4, 3, 9, 4, 16]

https://beginnersbug.com/transformation-and-action-in-pyspark/

https://beginnersbug.com/spark-sql-operation-in-pyspark/

Categories
unix

Deleting blank lines in a file using UNIX

In this post, let us learn about deleting blank lines in a file using UNIX.

Creating File with blank lines

I am having one file with the following as the content and also some blank/empty lines in it.

cat abc.txt
apple
Mango
Orange

Grapes

Peer

Pineapple

Using the below-given command, we can get to know the count of the line which includes the blank lines also.

wc -l abc.txt
9 abc.txt

This command lists the number of blank lines in a file.

^ – beginning of the line

$ – ending of the line

grep -c ^$ abc.txt
3

sed command helps us to delete the empty lines by checking for the matches.

sed -i '/^$/d' abc.txt

After the deletion, the File in the UNIX looks like below.

cat abc.txt
apple
Mango
Orange
Grapes
Peer
Pineapple

The count of the file after deleting the blank lines in a file using UNIX.

cat abc.txt |wc -l
6

Categories
python

Returning multiple values in python

In this post, let us learn about returning multiple values in python.

Will it possible in python?

Yes, returning multiple values in python is possible. There are several ways to do it.

1 . Return as Tuple :

The tuple stores the values of various datatypes. But we cannot modify those values in any case.

Please refer to the below link to understand it better.

https://beginnersbug.com/difference-between-list-and-tuple/

The tuple is created with or without a round bracket as below.

# Sample program to return as Tuple without bracket
def first():
 a="string"
 b=10
 return a,b
a,b=first()
print(a,b)

The above python function returns more than one value.

string 10

Tuple returns within a bracket as follows.

# Sample program to return as Tuple with bracket
def first():
 a="string"
 b=10
 return (a,b)
a,b=first()
print(a,b)
string 10
2 . Return as List :

The list is also a collection created with square bracket.

The list helps us in returning multiple values in python .

It is mutable in nature.

# Sample program to return as List
def second():
 a="apple"
 b=50
 return [a,b]
second_list=second()
print(second_list)

We return multiple values from the python function using the list.

['apple', 50]

We can identify the datatype of the return by using the below command

Categories
python

difference between list and tuple

In this post , let us learn about the difference between list and tuple.

What are Lists?

Lists are compound data types storing multiple independent values .

It can accommodate different datatypes like integer, string, float, etc., within a square bracket.

In the below example, we have different types of data getting created with the list.

# Creating lists with multiple datatypes 
a = [1, 2, 3, 'a', 'b', 'c', 'apple', 'orange', 10.89]
What are Tuples ?

Tuples are also one of the sequence datatypes as like Lists.

Tuples can be created by storing the data within round bracket or without any brackets.

#Creating tuple with round bracket
b=(1,2,3,'a','b','c','apple','orange',10.89,(6,7,8))
#Creating tuple without any brackets
c=1,2,3,'a','b','c','apple','orange',10.89,(6,7,8)
What is the difference between list and tuple?

Lists are mutable whereas tuples are immutable.

We can change the lists but not the tuples.

program
# Creating  list a
a=[1, 2, 3, 'a', 'b', 'c', 'apple', 'orange', 10.89]
# Displaying the data
a
# Displaying the datatype
type(a)
Result
[1, 2, 3, 'a', 'b', 'c', 'apple', 'orange', 10.89]
list

We can append the list as shown below, But we cannot change the tuple.

This is the difference between the tuple and the list.

program
# Trying to append data to it
a.append('d')
a
RESULT
[1, 2, 3, 'a', 'b', 'c', 'apple', 'orange', 10.89, 'd']