Dario  Schaden

Dario Schaden

1654315080

Pyramid Excel: Let You Focus on Data, Instead Of File formats

Support the project

If your company has embedded pyexcel and its components into a revenue generating product, please support me on github, patreon or bounty source to maintain the project and develop it further.

If you are an individual, you are welcome to support me too and for however long you feel like. As my backer, you will receive early access to pyexcel related contents.

And your issues will get prioritized if you would like to become my patreon as pyexcel pro user.

With your financial support, I will be able to invest a little bit more time in coding, documentation and writing interesting posts.

Known constraints

Fonts, colors and charts are not supported.

Introduction

Here is a typical conversation between the developer and the user:

User: "I have uploaded an excel file"
      "but your application says un-supported file format"
Developer: "Did you upload an xlsx file or a csv file?"
User: "Well, I am not sure. I saved the data using "
      "Microsoft Excel. Surely, it must be in an excel format."
Developer: "OK. Here is the thing. I were not told to support"
           "all available excel formats in day 1. Live with it"
           "or delay the project x number of days."

pyramid-excel is based on pyexcel and makes it easy to consume/produce information stored in excel files over HTTP protocol as well as on file system. This library can turn the excel data into a list of lists, a list of records(dictionaries), dictionaries of lists. And vice versa. Hence it lets you focus on data in Pyramid based web development, instead of file formats.

The idea originated from the common usability problem: when an excel file driven web application is delivered for non-developer users (ie: team assistant, human resource administrator etc). The fact is that not everyone knows (or cares) about the differences between various excel formats: csv, xls, xlsx are all the same to them. Instead of training those users about file formats, this library helps web developers to handle most of the excel file formats by providing a common programming interface. To add a specific excel file format type to you application, all you need is to install an extra pyexcel plugin. Hence no code changes to your application and no issues with excel file formats any more. Looking at the community, this library and its associated ones try to become a small and easy to install alternative to Pandas.

The highlighted features are:

  1. excel data import into and export from databases
  2. turn uploaded excel file directly into Python data structure
  3. pass Python data structures as an excel file download
  4. provide data persistence as an excel file in server side
  5. supports csv, tsv, csvz, tsvz by default and other formats are supported via the following plugins:

A list of file formats supported by external plugins

Package nameSupported file formatsDependencies
pyexcel-iocsv, csvz [1], tsv, tsvz [2] 
pyexcel-xlsxls, xlsx(read only), xlsm(read only)xlrd, xlwt
pyexcel-xlsxxlsxopenpyxl
pyexcel-ods3odspyexcel-ezodf, lxml
pyexcel-odsodsodfpy

Dedicated file reader and writers

Package nameSupported file formatsDependencies
pyexcel-xlsxwxlsx(write only)XlsxWriter
pyexcel-libxlsxwxlsx(write only)libxlsxwriter
pyexcel-xlsxrxlsx(read only)lxml
pyexcel-xlsbrxlsb(read only)pyxlsb
pyexcel-odsrread only for ods, fodslxml
pyexcel-odswwrite only for odsloxun
pyexcel-htmlrhtml(read only)lxml,html5lib
pyexcel-pdfrpdf(read only)camelot

Plugin shopping guide

Since 2020, all pyexcel-io plugins have dropped the support for python version lower than 3.6. If you want to use any python verions, please use pyexcel-io and its plugins version lower than 0.6.0.

Except csv files, xls, xlsx and ods files are a zip of a folder containing a lot of xml files

The dedicated readers for excel files can stream read

In order to manage the list of plugins installed, you need to use pip to add or remove a plugin. When you use virtualenv, you can have different plugins per virtual environment. In the situation where you have multiple plugins that does the same thing in your environment, you need to tell pyexcel which plugin to use per function call. For example, pyexcel-ods and pyexcel-odsr, and you want to get_array to use pyexcel-odsr. You need to append get_array(..., library='pyexcel-odsr').

Other data renderers

Package nameSupported file formatsDependenciesPython versions
pyexcel-textwrite only:rst, mediawiki, html, latex, grid, pipe, orgtbl, plain simple read only: ndjson r/w: jsontabulate2.6, 2.7, 3.3, 3.4 3.5, 3.6, pypy
pyexcel-handsontablehandsontable in htmlhandsontablesame as above
pyexcel-pygalsvg chartpygal2.7, 3.3, 3.4, 3.5 3.6, pypy
pyexcel-sortablesortable table in htmlcsvtotablesame as above
pyexcel-ganttgantt chart in htmlfrappe-ganttexcept pypy, same as above

Footnotes

[1]zipped csv file
[2]zipped tsv file

This library makes information processing involving various excel files as easy as processing array, dictionary when processing file upload/download, data import into and export from SQL databases, information analysis and persistence. It uses pyexcel and its plugins:

  1. to provide one uniform programming interface to handle csv, tsv, xls, xlsx, xlsm and ods formats.
  2. to provide one-stop utility to import the data in uploaded file into a database and to export tables in a database as excel files for file download.
  3. to provide the same interface for information persistence at server side: saving a uploaded excel file to and loading a saved excel file from file system.

Tested Pyramid Versions

So far pyexcel-xls plugin does not work with Python 3.9

Installation

You can install pyramid-excel via pip:

$ pip install pyramid-excel

or clone it and install it:

$ git clone https://github.com/pyexcel-webwares/pyramid-excel.git
$ cd pyramid-excel
$ python setup.py install

Setup

Once the pyramid_excel is installed, you must use the config.include mechanism to include it into your Pyramid project's configuration:

config = Configurator(.....)
config.include('pyramid_excel')

Alternately, you may activate the extension by changing your application's .ini file by adding it to the pyramid.includes list:

pyramid.includes = pyramid_excel

Development guide

Development steps for code changes

  1. git clone https://github.com/pyexcel/pyramid-excel.git
  2. cd pyramid-excel

Upgrade your setup tools and pip. They are needed for development and testing only:

  1. pip install --upgrade setuptools pip

Then install relevant development requirements:

  1. pip install -r rnd_requirements.txt # if such a file exists
  2. pip install -r requirements.txt
  3. pip install -r tests/requirements.txt

Once you have finished your changes, please provide test case(s), relevant documentation and update CHANGELOG.rst.

Note

As to rnd_requirements.txt, usually, it is created when a dependent library is not released. Once the dependecy is installed (will be released), the future version of the dependency in the requirements.txt will be valid.

How to test your contribution

Although nose and doctest are both used in code testing, it is adviable that unit tests are put in tests. doctest is incorporated only to make sure the code examples in documentation remain valid across different development releases.

On Linux/Unix systems, please launch your tests like this:

$ make

On Windows systems, please issue this command:

> test.bat

Before you commit

Please run:

$ make format

so as to beautify your code otherwise travis-ci may fail your unit test.

Author: pyexcel-webwares
Source Code: https://github.com/pyexcel-webwares/pyramid-excel
License: View license

#python #pyramid #excel 

What is GEEK

Buddha Community

Pyramid Excel: Let You Focus on Data, Instead Of File formats
Gerhard  Brink

Gerhard Brink

1622622360

Data Validation in Excel

Data Validation in Excel

In this tutorial, let’s discuss what data validation is and how it can be implemented in MS-Excel. Let’s start!!!

What Is Data Validation in Excel?

Data Validation is one of the features in MS-Excel which helps in maintaining the consistency of the data in the spreadsheet. It controls the type of data that can enter in the data validated cells.

Data Validation in MS Excel

Now, let’s have a look at how data validation works and how to implement it in the worksheet:

To apply data validation for the cells, then follow the steps.

1: Choose to which all cells the validation of data should work.

2: Click on the DATA tab.

3: Go to the Data Validation option.

4: Choose the drop down option in it and click on the Data Validation.

data validation in Excel

Once you click on the data validation menu from the ribbon, a box appears with the list of data validation criteria, Input message and error message.

Let’s first understand, what is an input message and error message?

Once, the user clicks the cell, the input message appears in a small box near the cell.

If the user violates the condition of that particular cell, then the error message pops up in a box in the spreadsheet.

The advantage of both the messages is that the input and as well as the error message guide the user about how to fill the cells. Both the messages are customizable also.

Let us have a look at how to set it up and how it works with a sample

#ms excel tutorials #circle invalid data in excel #clear validation circles in excel #custom data validation in excel #data validation in excel #limitation in data validation in excel #setting up error message in excel #setting up input message in excel #troubleshooting formulas in excel #validate data in excel

Lina  Biyinzika

Lina Biyinzika

1678051620

A Practical Guide of Unsupervised Learning Algorithms

In this article, learn about Machine Learning Tutorial: A Practical  Guide of Unsupervised Learning Algorithms. Machine learning is a fast-growing technology that allows computers to learn from the past and predict the future. It uses numerous algorithms for building mathematical models and predicting future trends. Machine learning (ML) has widespread applications in the industry, including speech recognition, image recognition, churn prediction, email filtering, chatbot development, recommender systems, and much more.

Machine learning (ML) can be classified into three main categories; supervised, unsupervised, and reinforcement learning. In supervised learning, the model is trained on labeled data. While in unsupervised learning, unlabeled data is provided to the model to predict the outcomes. Reinforcement learning is feedback learning in which the agent collects a reward for each correct action and gets a penalty for a wrong decision. The goal of the learning agent is to get maximum reward points and deduce the error.

What is Unsupervised Learning?

In unsupervised learning, the model learns from unlabeled data without proper supervision.

Unsupervised learning uses machine learning techniques to cluster unlabeled data based on similarities and differences. The unsupervised algorithms discover hidden patterns in data without human supervision. Unsupervised learning aims to arrange the raw data into new features or groups together with similar patterns of data.

For instance, to predict the churn rate, we provide unlabeled data to our model for prediction. There is no information given that customers have churned or not. The model will analyze the data and find hidden patterns to categorize into two clusters: churned and non-churned customers.

Unsupervised Learning Approaches

Unsupervised algorithms can be used for three tasks—clustering, dimensionality reduction, and association. Below, we will highlight some commonly used clustering and association algorithms.

Clustering Techniques

Clustering, or cluster analysis, is a popular data mining technique for unsupervised learning. The clustering approach works to group non-labeled data based on similarities and differences. Unlike supervised learning, clustering algorithms discover natural groupings in data. 

A good clustering method produces high-quality clusters having high intra-class similarity (similar data within a cluster) and less intra-class similarity (cluster data is dissimilar to other clusters). 

It can be defined as the grouping of data points into various clusters containing similar data points. The same objects remain in the group that has fewer similarities with other groups. Here, we will discuss two popular clustering techniques: K-Means clustering and DBScan Clustering.

K-Means Clustering

K-Means is the simplest unsupervised technique used to solve clustering problems. It groups the unlabeled data into various clusters. The K value defines the number of clusters you need to tell the system how many to create.

K-Means is a centroid-based algorithm in which each cluster is associated with the centroid. The goal is to minimize the sum of the distances between the data points and their corresponding clusters.

It is an iterative approach that breaks down the unlabeled data into different clusters so that each data point belongs to a group with similar characteristics.

K-means clustering performs two tasks:

  1. Using an iterative process to create the best value of K.
  2. Each data point is assigned to its closest k-center. The data point that is closer to the particular k-center makes a cluster.

 

An illustration of K-means clustering. Image source

DBScan Clustering

“DBScan” stands for “Density-based spatial clustering of applications with noise.” There are three main words in DBscan: density, clustering, and noise. Therefore, this algorithm uses the notion of density-based clustering to form clusters and detect the noise.

Clusters are usually dense regions that are separated by lower density regions. Unlike the k-means algorithm, which works only on well-separated clusters, DBscan has a wider scope and can create clusters within the cluster. It discovers clusters of various shapes and sizes from a large set of data, which consists of noise and outliers.

There are two parameters in the DBScan algorithm:

minPts: The threshold, or the minimum number of points grouped together for a region considered as a dense region.

eps(ε): The distance measure used to locate the points in the neighborhood. 

dbscan-clustering

 

An illustration of density-based clustering. Image Source 

Association Rule Mining

An association rule mining is a popular data mining technique. It finds interesting correlations in large numbers of data items. This rule shows how frequently items occur in a transaction.

Market Basket Analysis is a typical example of an association rule mining that finds relationships between items in the grocery store. It enables retailers to identify and analyze the associations between items that people frequently buy.

Important terminology used in association rules:

Support: It tells us about the combination of items bought frequently or frequently bought items.

Confidence: It tells us how often the items A and B occur together, given the number of times A occurs.

Lift: The lift indicates the strength of a rule over the random occurrence of A and B. For instance, A->B, the life value is 5. It means that if you buy A, the occurrence of buying B is five times.

The Apriori algorithm is a well-known association rule based technique.

Apriori algorithm 

The Apriori algorithm was proposed by R. Agarwal and R. Srikant in 1994 to find the frequent items in the dataset. The algorithm’s name is based on the fact that it uses prior knowledge of frequently occurring things. 

The Apriori algorithm finds frequently occurring items with minimum support. 

It consists of two steps:

  • Generation of candidate itemsets.
  • Removing items that are infrequent and don’t fulfill the criteria of minimum support.

Practical Implementation of Unsupervised Algorithms 

In this tutorial, you will learn about the implementation of various unsupervised algorithms in Python. Scikit-learn is a powerful Python library widely used for various unsupervised learning tasks. It is an open-source library that provides numerous robust algorithms, which include classification, dimensionality reduction, clustering techniques, and association rules.

Let’s begin!

1. K-Means algorithm 

Now let’s dive deep into the implementation of the K-Means algorithm in Python. We’ll break down each code snippet so that you can understand it easily.

Import libraries

First of all, we will import the required libraries and get access to the functions.

#Let's import the required libraries
import numpy as np
import pandas as pd 
import matplotlib.pyplot as plt
import seaborn as sns

Loading the dataset 

The dataset is taken from the kaggle website. You can easily download it from the given link. To load the dataset, we use the pd.read_csv() function. head() returns the first five rows of the dataset.

my_data = pd.read_csv('Customers_Mall.csv.') my_data.head() dataset-columns

The dataset contains five columns: customer ID, gender, age, annual income in (K$), and spending score from 1-100. 

Data Preprocessing 

The info() function is used to get quick information about the dataset. It shows the number of entries, columns, total non-null values, memory usage, and datatypes. 

my_data.info()

dataset-description

 

To check the missing values in the dataset, we use isnull().sum(), which returns the total number of null values.

 

#Check missing values 
my_data.isnull().sum()

dataset-null-values

 

The box plot or whisker plot is used to detect outliers in the dataset. It also shows a statistical five number summary, which includes the minimum, first quartile, median (2nd quartile), third quartile, and maximum.

my_data.boxplot(figsize=(8,4)) dataset-boxplot-detect-outliers

Using Box Plot, we’ve detected an outlier in the annual income column. Now we will try to remove it before training our model. 

#let's remove outlier from data
med =61
my_data["Annual Income (k$)"] = np.where(my_data["Annual Income (k$)"] >
 120,med,my_data['Annual Income (k$)'])


The outlier in the annual income column has been removed now to confirm we used the box plot again.

my_data.boxplot(figsize=(8,5)) outlier-removed

Data Visualization

A histogram is used to illustrate the important features of the distribution of data. The hist() function is used to show the distribution of data in each numerical column.

my_data.hist(figsize=(6,6)) 

The correlation heatmap is used to find the potential relationships between variables in the data and to display the strength of those relationships. To display the heatmap, we have used the seaborn plotting library.

plt.figure(figsize=(10,6)) sns.heatmap(my_data.corr(), annot=True, cmap='icefire').set_title('seaborn') plt.show() dataset-histogram

Choosing the Best K Value

The iloc() function is used to select a particular cell of the data. It enables us to select a value that belongs to a specific row or column. Here, we’ve chosen the annual income and spending score columns.

 

X_val = my_data.iloc[:, 3:].values X_val

 

# Loading Kmeans Library

from sklearn.cluster import KMeans

Now we will select the best value for K using the Elbow’s method. It is used to determine the optimal number of clusters in K-means clustering.

my_val = []

for i in range(1,11):

    kmeans = KMeans(n_clusters = i, init='k-means++', random_state = 123)

    kmeans.fit(X_val)

    my_val.append(kmeans.inertia_)

The sklearn.cluster.KMeans() is used to choose the number of clusters along with the initialization of other parameters. To display the result, just call the variable.

my_val dataset-iloc-function #Visualization of clusters using elbow’s method plt.plot(range(1,11),my_val) plt.xlabel('The No of clusters') plt.ylabel('Outcome') plt.title('The Elbow Method') plt.show() clusters-elbow-method

Through Elbow’s Method, when the graph looks like an arm, then the elbow on the arm is the best value of K. In this case, we’ve taken K=3, which is the optimal value for K.

kmeans = KMeans(n_clusters = 3, init='k-means++') kmeans.fit(X_val) number-of-clusters #To show centroids of clusters  kmeans.cluster_centers_ cluster-centers #Prediction of K-Means clustering  y_kmeans = kmeans.fit_predict(X_val) y_kmeans

fit-predict-function-kmeans

Splitting the dataset into three clusters

The scatter graph is used to plot the classification results of our dataset into three clusters.

plt.scatter(X_val[y_kmeans == 0,0], X_val[y_kmeans == 0,1], c='red',s=100)

plt.scatter(X_val[y_kmeans == 1,0], X_val[y_kmeans == 1,1], c='green',s=100)

plt.scatter(X_val[y_kmeans == 2,0], X_val[y_kmeans == 2,1], c='orange',s=100)

plt.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], s=300, c='brown')

plt.title('K-Means Unsupervised Learning')

plt.show()


2. Apriori Algorithm

To implement the apriori algorithm, we will utilize “The Bread Basket” dataset. The dataset is available on Kaggle and you can download it from the link. This algorithm suggests products based on the user’s purchase history. Walmart has greatly utilized the algorithm to recommend relevant items to its users.

Let’s implement the Apriori algorithm in Python. 

Import libraries 

To implement the algorithm, we need to import some important libraries.

import pandas as pd

import matplotlib.pyplot as plt

import numpy as np

import seaborn as sns

Loading the dataset 

The dataset contains five columns and 20507 entries. The data_time is a prominent column and we can extract many vital insights from it.

my_data= pd.read_csv("bread basket.csv") my_data.head() bread-basket-dataset-apriori

Data Preprocessing 

Convert the data_time into an appropriate format.

my_data['date_time'] = pd.to_datetime(my_data['date_time'])

#Total No of unique customers

my_data['Transaction'].nunique()

unique-customers-apriori

Now we want to extract new columns from the data_time to extract meaningful information from the data.

#Let's extract date

my_data['date'] = my_data['date_time'].dt.date

#Let's extract time

my_data['time'] = my_data['date_time'].dt.time

#Extract month and replacing it with String

my_data['month'] = my_data['date_time'].dt.month

my_data['month'] = my_data['month'].replace((1,2,3,4,5,6,7,8,9,10,11,12), 

                                          ('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug',

                                          'Sep','Oct','Nov','Dec'))

#Extract hour

my_data[‘hour’] = my_data[‘date_time’].dt.hour

# Replacing hours with text

# Replacing hours with text

hr_num = (1,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23)

hr_obj = (‘1-2′,’7-8′,’8-9′,’9-10′,’10-11′,’11-12′,’12-13′,’13-14′,’14-15’,

               ’15-16′,’16-17′,’17-18′,’18-19′,’19-20′,’20-21′,’21-22′,’22-23′,’23-24′)

my_data[‘hour’] = my_data[‘hour’].replace(hr_num, hr_obj)

# Extracting weekday and replacing it with String 

my_data[‘weekday’] = my_data[‘date_time’].dt.weekday

my_data[‘weekday’] = my_data[‘weekday’].replace((0,1,2,3,4,5,6), 

                                          (‘Mon’,’Tues’,’Wed’,’Thur’,’Fri’,’Sat’,’Sun’))

#Now drop date_time column

my_data.drop(‘date_time’, axis = 1, inplace = True)

After extracting the date, time, month, and hour columns, we dropped the data_time column.

Now to display, we simply use the head() function to see the changes in the dataset.

my_data.head()

dataset-apriori

# cleaning the item column

my_data[‘Item’] = my_data[‘Item’].str.strip()

my_data[‘Item’] = my_data[‘Item’].str.lower()

my_data.head()

clean-dataset

Data Visualization 

To display the top 10 items purchased by customers, we used a barplot() of the seaborn library. 

plt.figure(figsize=(10,5))

sns.barplot(x=my_data.Item.value_counts().head(10).index, y=my_data.Item.value_counts().head(10).values,palette='RdYlGn')

plt.xlabel('No of Items', size = 17)

plt.xticks(rotation=45)

plt.ylabel('Total Items', size = 18)

plt.title('Top 10 Items purchased', color = 'blue', size = 23)

plt.show()


From the graph, coffee is the top item purchased by the customers, followed by bread.

Now, to display the number of orders received each month, the groupby() function is used along with barplot() to visually show the results.

mon_Tran =my_data.groupby('month')['Transaction'].count().reset_index() mon_Tran.loc[:,"mon_order"] =[4,8,12,2,1,7,6,3,5,11,10,9] mon_Tran.sort_values("mon_order",inplace=True) plt.figure(figsize=(12,5)) sns.barplot(data = mon_Tran, x = "month", y = "Transaction") plt.xlabel('Months', size = 14) plt.ylabel('Monthly Orders', size = 14) plt.title('No of orders received each month', color = 'blue', size = 18) plt.show() orders-received-dataset

To show the number of orders received each day, we applied groupby() to the weekday column.

wk_Tran = my_data.groupby('weekday')['Transaction'].count().reset_index()

wk_Tran.loc[:,"wk_ord"] = [4,0,5,6,3,1,2]

wk_Tran.sort_values("wk_ord",inplace=True)

plt.figure(figsize=(11,4))

sns.barplot(data = wk_Tran, x = "weekday", y = "Transaction",palette='RdYlGn')

plt.xlabel('Week Day', size = 14)

plt.ylabel('Per day orders', size = 14)

plt.title('Orders received per day', color = 'blue', size = 18)

plt.show()


 Implementation of the Apriori Algorithm 

We import the mlxtend library to implement the association rules and count the number of items.

from mlxtend.frequent_patterns import association_rules, apriori

tran_str= my_data.groupby(['Transaction', 'Item'])['Item'].count().reset_index(name ='Count')

tran_str.head(8)

association-rule-mixtend

Now we’ll make a mxn matrix where m=transaction and n=items, and each row represents whether the item was in the transaction or not.

Mar_baskt = tran_str.pivot_table(index='Transaction', columns='Item', values='Count', aggfunc='sum').fillna(0)

Mar_baskt.head()

market-basket

We want to make a function that returns 0 and 1. 0 means that the item wasn’t present in the transaction, while 1 means the item exists.

def encode(val):

    if val<=0:

        return 0

    if val>=1:

        return 1

#Let's apply the function to the dataset

Basket=Mar_baskt.applymap(encode)

Basket.head()

basket-head

#using apriori algorithm to set min_support 0.01 means 1% freq_items = apriori(Basket, min_support = 0.01,use_colnames = True) freq_items.head()

frequent-items-apriori

Using the association_rules() function to generate the most frequent items from the dataset.

App_rule= association_rules(freq_items, metric = "lift", min_threshold = 1) App_rule.sort_values('confidence', ascending = False, inplace = True) App_rule.head() association-rules-apriori

From the above implementation, the most frequent items are coffee and toast, both having a lift value of 1.47 and a confidence value of 0.70. 

3. Principal Component Analysis 

Principal component analysis (PCA) is one of the most widely used unsupervised learning techniques. It can be used for various tasks, including dimensionality reduction, information compression, exploratory data analysis and Data de-noising.

Let’s use the PCA algorithm!

First we import the required libraries to implement this algorithm.

import numpy as np 

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns

%matplotlib inline

from sklearn.decomposition import PCA

from sklearn.datasets import load_digits

Loading the Dataset 

To implement the PCA algorithm the load_digits dataset of Scikit-learn is used which can easily be loaded using the below command. The dataset contains images data which include 1797 entries and 64 columns.

 

#Load the dataset

my_data= load_digits()

#Creating features

X_value = my_data.data

#Creating target

#Let's check the shape of X_value

X_value.shape

 

dataset-X-shape

 

 

#Each image is 8x8 pixels therefore 64px  my_data.images[10] image-pixels #Let's display the image plt.gray()  plt.matshow(my_data.images[34])  plt.show()

image-pixels

Now let’s project data from 64 columns to 16 to show how 16 dimensions classify the data.

X_val = my_data.data 

y_val = my_data.target

my_pca = PCA(16)  

X_projection = my_pca.fit_transform(X_val)

print(X_val.shape)

print(X_projection.shape)

projection-shape

Using colormap we visualize that with only ten dimensions  we can classify the data points. Now we’ll select the optimal number of dimensions (principal components) by which data can be reduced into lower dimensions.

plt.scatter(X_projection[:, 0], X_projection[:, 1], c=y_val, edgecolor='white',

            cmap=plt.cm.get_cmap("gist_heat",12))

plt.colorbar();

x-projection

pca=PCA().fit(X_val)

plt.plot(np.cumsum(my_pca.explained_variance_ratio_))

plt.xlabel('Principal components')

plt.ylabel('Explained variance')

Based on the below graph, only 12 components are required to explain more than 80% of the variance which is still better than computing all the 64 features. Thus, we’ve reduced the large number of dimensions into 12 dimensions to avoid the dimensionality curse. pca=PCA().fit(X_val)

plt.plot(np.cumsum(pca.explained_variance_ratio_))

plt.xlabel('Principal components')

plt.ylabel('Explained variance')



#Let's visualize how it looks like

Unsupervised_pca = PCA(12)  

X_pro = Unsupervised_pca.fit_transform(X_val)

print("New Data Shape is =>",X_pro.shape)

#Let's Create a scatter plot

plt.scatter(X_pro[:, 0], X_pro[:, 1], c=y_val, edgecolor='white',

            cmap=plt.cm.get_cmap("nipy_spectral",10))

plt.colorbar();


principal-component-analysis

Wrapping Up 

beyond machine

In this machine learning tutorial, we’ve implemented the Kmeans, Apriori, and PCA algorithms. These are some of the most widely used algorithms, having numerous industrial applications and solve many real world problems. For instance, K-means clustering is used in astronomy to study stellar and galaxy spectra, solar polarization spectra, and X-ray spectra. And, Apriori is used by retail stores to optimize their product inventory. 

Dreaming of becoming a data scientist or data analyst even without a university and a college degree? Do you need the knowledge of data science and analysis for promotions in your current role?

Are you interested in securing your dream job in data science and analysis and looking for a way to get started, we can help you? With over 10 years of experience in data science and data analysis, we will teach you the rubrics, guiding you with one-on-one lessons from the fundamentals until you become a pro.

Our courses are affordable and easy to understand with numerous exercises and assignments you can learn from. At the completion of our courses, you’ll be readily equipped with technical and practical skills to take on any data science and data analysis role in companies, collaborate effectively among teams and help businesses meet and exceed their objectives by extracting actionable insights from data.

Original article sourced at: https://thedatascientist.com

#machine-learning 

 iOS App Dev

iOS App Dev

1620466520

Your Data Architecture: Simple Best Practices for Your Data Strategy

If you accumulate data on which you base your decision-making as an organization, you should probably think about your data architecture and possible best practices.

If you accumulate data on which you base your decision-making as an organization, you most probably need to think about your data architecture and consider possible best practices. Gaining a competitive edge, remaining customer-centric to the greatest extent possible, and streamlining processes to get on-the-button outcomes can all be traced back to an organization’s capacity to build a future-ready data architecture.

In what follows, we offer a short overview of the overarching capabilities of data architecture. These include user-centricity, elasticity, robustness, and the capacity to ensure the seamless flow of data at all times. Added to these are automation enablement, plus security and data governance considerations. These points from our checklist for what we perceive to be an anticipatory analytics ecosystem.

#big data #data science #big data analytics #data analysis #data architecture #data transformation #data platform #data strategy #cloud data platform #data acquisition

Создание пагинации с помощью jQuery

В этой статье мы увидим, как создать пагинацию с помощью jquery. Мы создадим разбиение на страницы jquery, используя несколько способов. Вы можете создать разбиение на страницы, используя разные способы, такие как создание разбиения на страницы с помощью простого HTML, вы можете создать разбиение на страницы в laravel, используя метод paginate(). Кроме того, создайте разбиение на страницы laravel livewire, разбиение на страницы с помощью бутстрапа.

Мы создадим простую пагинацию jquery. Кроме того, создайте разбиение на страницы с помощью jquery без плагина и создайте разбивку на страницы jquery с помощью кнопок «Далее» и «Предыдущий».

Итак, давайте посмотрим динамическую нумерацию страниц в jquery и бутстраповскую нумерацию страниц в jquery.

Пример:

В этом примере мы создадим пагинацию с помощью jquery без использования плагина. Кроме того, вы можете настроить пагинацию.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>How To Create Pagination Using jQuery - Websolutionstuff</title>
        <style>
            .current {
            color: green;
            }

            #pagin li {
            display: inline-block;
            font-weight: 500;
            }

            .prev {
            cursor: pointer;
            }

            .next {
            cursor: pointer;
            }

            .last {
            cursor:pointer;
            margin-left:10px;
            }

            .first {
            cursor:pointer;
            margin-right:10px;
            }

            .line-content, #pagin, h3 {
            text-align:center;
            }

            .line-content {
            margin-top:20px;
            }

            #pagin {
            margin-top:10px;
            padding-left:0;
            }

            h3 {
            margin:50px 0;  
            }
        </style>
    </head>
    <body>
        <h3>How To Create Pagination Using jQuery - Websolutionstuff</h3>
        <div class="line-content">This is Page 1 content example with next and prev.</div>
        <div class="line-content">This is Page 2 content example with next and prev.</div>
        <div class="line-content">This is Page 3 content example with next and prev.</div>
        <div class="line-content">This is Page 4 content example with next and prev.</div>
        <div class="line-content">This is Page 5 content example with next and prev.</div>
        <div class="line-content">This is Page 6 content example with next and prev.</div>
        <div class="line-content">This is Page 7 content example with next and prev.</div>
        <div class="line-content">This is Page 8 content example with next and prev.</div>
        <div class="line-content">This is Page 9 content example with next and prev.</div>
        <div class="line-content">This is Page 10 content example with next and prev.</div>
        <div class="line-content">This is Page 11 content example with next and prev.</div>
        <div class="line-content">This is Page 12 content example with next and prev.</div>
        <div class="line-content">This is Page 13 content example with next and prev.</div>
        <div class="line-content">This is Page 14 content example with next and prev.</div>
        <div class="line-content">This is Page 15 content example with next and prev.</div>
        <div class="line-content">This is Page 16 content example with next and prev.</div>
        <div class="line-content">This is Page 17 content example with next and prev.</div>
        <div class="line-content">This is Page 18 content example with next and prev.</div>
        <div class="line-content">This is Page 19 content example with next and prev.</div>
        <div class="line-content">This is Page 20 content example with next and prev.</div>
        <div class="line-content">This is Page 21 content example with next and prev.</div>
        <div class="line-content">This is Page 22 content example with next and prev.</div>
        <div class="line-content">This is Page 23 content example with next and prev.</div>
        <div class="line-content">This is Page 24 content example with next and prev.</div>
        <div class="line-content">This is Page 25 content example with next and prev.</div>
        <div class="line-content">This is Page 26 content example with next and prev.</div>
        <div class="line-content">This is Page 27 content example with next and prev.</div>
        <div class="line-content">This is Page 28 content example with next and prev.</div>
        <div class="line-content">This is Page 29 content example with next and prev.</div>
        <div class="line-content">This is Page 30 content example with next and prev.</div>
        <div class="line-content">This is Page 31 content example with next and prev.</div>
        <div class="line-content">This is Page 32 content example with next and prev.</div>
        <div class="line-content">This is Page 33 content example with next and prev.</div>
        <div class="line-content">This is Page 34 content example with next and prev.</div>
        <div class="line-content">This is Page 35 content example with next and prev.</div>
        <div class="line-content">This is Page 36 content example with next and prev.</div>
        <div class="line-content">This is Page 37 content example with next and prev.</div>
        <div class="line-content">This is Page 38 content example with next and prev.</div>
        <div class="line-content">This is Page 39 content example with next and prev.</div>
        <div class="line-content">This is Page 40 content example with next and prev.</div>
        <div class="line-content">This is Page 41 content example with next and prev.</div>
        <div class="line-content">This is Page 42 content example with next and prev.</div>
        <div class="line-content">This is Page 43 content example with next and prev.</div>
        <div class="line-content">This is Page 44 content example with next and prev.</div>
        <div class="line-content">This is Page 45 content example with next and prev.</div>
        <ul id="pagin"></ul>
    </body>
</html>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script>

pageSize = 5;
incremSlide = 5;
startPage = 0;
numberPage = 0;

var pageCount =  $(".line-content").length / pageSize;
var totalSlidepPage = Math.floor(pageCount / incremSlide);
    
for(var i = 0 ; i<pageCount;i++){
    $("#pagin").append('<li><a href="#">'+(i+1)+'</a></li> ');
    if(i>pageSize){
       $("#pagin li").eq(i).hide();
    }
}

var prev = $("<li/>").addClass("prev").html("Prev").click(function(){
    startPage-=5;
    incremSlide-=5;
    numberPage--;
    slide();
});

prev.hide();

var next = $("<li/>").addClass("next").html("Next").click(function(){
    startPage+=5;
    incremSlide+=5;
    numberPage++;
    slide();
});

$("#pagin").prepend(prev).append(next);

$("#pagin li").first().find("a").addClass("current");

slide = function(sens){
    $("#pagin li").hide();
   
    for(t=startPage;t<incremSlide;t++){
        $("#pagin li").eq(t+1).show();
    }
    if(startPage == 0){
        next.show();
        prev.hide();
    }else if(numberPage == totalSlidepPage ){
        next.hide();
        prev.show();
    }else{
        next.show();
        prev.show();
    }    
}

showPage = function(page) {
    $(".line-content").hide();
    $(".line-content").each(function(n) {
        if (n >= pageSize * (page - 1) && n < pageSize * page){
            $(this).show();
        }
    });        
}
    
showPage(1);
$("#pagin li a").eq(0).addClass("current");

$("#pagin li a").click(function() {
    $("#pagin li a").removeClass("current");
    $(this).addClass("current");
    showPage(parseInt($(this).text()));
});
</script>

Выход:

как_to_create_pagination_using_jquery_output

Пример:

В этом примере мы создадим загрузочную пагинацию с помощью jquery.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>How To Create Bootstrap Pagination Using jQuery - Websolutionstuff</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
        <style>
            #data tr {
                display: none;
            }

            .page {
                margin: 30px;
            }

            table, th, td {
                border: 1px solid black;
            }

            #data {
                font-family: Arial, Helvetica, sans-serif;
                border-collapse: collapse;
                width: 100%;
            }

            #data td, #data th {
                border: 1px solid #ddd;
                padding: 8px;
            }

            #data tr:nth-child(even) {
                background-color: #f2f2f2;
            }

            #data tr:hover {
                background-color: #ddd;
            }

            #data th {
                padding-top: 12px;
                padding-bottom: 12px;
                text-align: left;
                background-color: #03aa96;
                color: white;
            }

            #nav a {
                color: #03aa96;
                font-size: 20px;
                margin-top: 22px;
                font-weight: 600;
            }

            a:hover, a:visited, a:link, a:active {
                text-decoration: none;
            }

            #nav {
                margin-top: 20px;
            }
        </style>
    </head>
    <body>                  
        <h2 align="center" class="mt-4">How To Create Bootstrap Pagination Using jQuery - Websolutionstuff</h2>
        <div class="page" align="center">   
            <table id="data">  
                <tr>  
                    <th>Id</th>  
                    <th>Name</th>  
                    <th>Country</th>  
                </tr>  
                <tr>  
                    <td>1</td>  
                    <td>Maria</td>  
                    <td>Germany</td>  
                </tr>  
                <tr>  
                    <td>2</td>  
                    <td>Christina</td>  
                    <td>Sweden</td>  
                </tr>  
                <tr>  
                    <td>3</td>  
                    <td>Chang</td>  
                    <td>Mexico</td>  
                </tr>  
                <tr>  
                    <td>4</td>  
                    <td>Mendel</td>  
                    <td>Austria</td>  
                </tr>  
                <tr>  
                    <td>5</td>  
                    <td>Helen</td>  
                    <td>United Kingdom</td>  
                </tr>  
                <tr>  
                    <td>6</td>  
                    <td>Philip</td>  
                    <td>Germany</td>  
                </tr>  
                <tr>  
                    <td>7</td>  
                    <td>Tannamuri</td>  
                    <td>Canada</td>  
                </tr>  
                <tr>  
                    <td>8</td>  
                    <td>Rovelli</td>  
                    <td>Italy</td>  
                </tr>  
                <tr>  
                    <td>9</td>  
                    <td>Dell</td>
                    <td>United Kingdom</td>
                </tr>  
                <tr>  
                    <td>10</td>  
                    <td>Trump</td>  
                    <td>France</td>  
                </tr>  
            </table>  
        </div>
    </body>
</html>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script>
$(document).ready (function () {  
    $('#data').after ('<div id="nav"></div>');  
    var rowsShown = 5;  
    var rowsTotal = $('#data tbody tr').length;  
    var numPages = rowsTotal/rowsShown;  
    for (i = 0;i < numPages;i++) {  
        var pageNum = i + 1;  
        $('#nav').append ('<a href="#" rel="'+i+'">'+pageNum+'</a> ');  
    }  
    $('#data tbody tr').hide();  
    $('#data tbody tr').slice (0, rowsShown).show();  
    $('#nav a:first').addClass('active');  
    $('#nav a').bind('click', function() {  
    $('#nav a').removeClass('active');  
    $(this).addClass('active');  
        var currPage = $(this).attr('rel');  
        var startItem = currPage * rowsShown;  
        var endItem = startItem + rowsShown;  
        $('#data tbody tr').css('opacity','0.0').hide().slice(startItem, endItem).  
        css('display','table-row').animate({opacity:1}, 300);  
    });  
});
</script>

Выход:

как_to_create_pagination_using_jquery_and_bootstrap

Пример:

В этом примере мы создадим пагинацию с помощью плагина twbsPagination . Этот плагин jQuery упрощает использование разбиения на страницы Bootstrap.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>jQuery Pagination Using Plugin - Websolutionstuff</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
        <style>
            .wrapper{
                margin: 60px auto;
                text-align: center;
            }
            h2{
                margin-bottom: 1.25em;
            }
            
            #pagination-demo{
                display: inline-block;
                margin-bottom: 1.75em;
            }

            #pagination-demo li{
                display: inline-block;
            }

            .page-content{
                background: #eee;
                display: inline-block;
                padding: 10px;
                width: 100%;
                max-width: 660px;
            }
        </style>
    </head>
    <body>                  
        <div class="wrapper">
            <div class="container">
              
              <div class="row">
                <div class="col-sm-12">
                  <h2>jQuery Pagination Using Plugin - Websolutionstuff</h2>
                  <p>Simple pagination using the TWBS pagination JS library.</p>
                  <ul id="pagination-demo" class="pagination-sm"></ul>
                </div>
              </div>
          
              <div id="page-content" class="page-content">Page 1</div>
            </div>
          </div>
    </body>
</html>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twbs-pagination/1.4.1/jquery.twbsPagination.min.js"></script>
<script>
$(document).ready (function () {  
    $('#pagination-demo').twbsPagination({
        totalPages: 16,
        visiblePages: 6,
        next: 'Next',
        prev: 'Prev',
        onPageClick: function (event, page) {            
            $('#page-content').text('Page ' + page) + ' content here';
        }
    });
});
</script>

Выход:

jquery_pagination_using_plugin

Оригинальный источник статьи: https://websolutionstuff.com/

#jquery #pagination 

Create Pagination Using jQuery

In this article, we will see how to create pagination using jquery. We will create jquery pagination using multiple ways. You can create pagination using different ways like creating pagination using simple HTML, you can create pagination in laravel using paginate() method. Also, create pagination laravel livewire, pagination using bootstrap.

We will create simple jquery pagination. Also, create pagination using jquery without a plugin and create jquery pagination with next and previous buttons

So, let's see dynamic pagination in jquery and bootstrap pagination in jquery

Example:

In this example, we will create pagination using jquery without using a plugin. Also, you can customize the pagination.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>How To Create Pagination Using jQuery - Websolutionstuff</title>
        <style>
            .current {
            color: green;
            }

            #pagin li {
            display: inline-block;
            font-weight: 500;
            }

            .prev {
            cursor: pointer;
            }

            .next {
            cursor: pointer;
            }

            .last {
            cursor:pointer;
            margin-left:10px;
            }

            .first {
            cursor:pointer;
            margin-right:10px;
            }

            .line-content, #pagin, h3 {
            text-align:center;
            }

            .line-content {
            margin-top:20px;
            }

            #pagin {
            margin-top:10px;
            padding-left:0;
            }

            h3 {
            margin:50px 0;  
            }
        </style>
    </head>
    <body>
        <h3>How To Create Pagination Using jQuery - Websolutionstuff</h3>
        <div class="line-content">This is Page 1 content example with next and prev.</div>
        <div class="line-content">This is Page 2 content example with next and prev.</div>
        <div class="line-content">This is Page 3 content example with next and prev.</div>
        <div class="line-content">This is Page 4 content example with next and prev.</div>
        <div class="line-content">This is Page 5 content example with next and prev.</div>
        <div class="line-content">This is Page 6 content example with next and prev.</div>
        <div class="line-content">This is Page 7 content example with next and prev.</div>
        <div class="line-content">This is Page 8 content example with next and prev.</div>
        <div class="line-content">This is Page 9 content example with next and prev.</div>
        <div class="line-content">This is Page 10 content example with next and prev.</div>
        <div class="line-content">This is Page 11 content example with next and prev.</div>
        <div class="line-content">This is Page 12 content example with next and prev.</div>
        <div class="line-content">This is Page 13 content example with next and prev.</div>
        <div class="line-content">This is Page 14 content example with next and prev.</div>
        <div class="line-content">This is Page 15 content example with next and prev.</div>
        <div class="line-content">This is Page 16 content example with next and prev.</div>
        <div class="line-content">This is Page 17 content example with next and prev.</div>
        <div class="line-content">This is Page 18 content example with next and prev.</div>
        <div class="line-content">This is Page 19 content example with next and prev.</div>
        <div class="line-content">This is Page 20 content example with next and prev.</div>
        <div class="line-content">This is Page 21 content example with next and prev.</div>
        <div class="line-content">This is Page 22 content example with next and prev.</div>
        <div class="line-content">This is Page 23 content example with next and prev.</div>
        <div class="line-content">This is Page 24 content example with next and prev.</div>
        <div class="line-content">This is Page 25 content example with next and prev.</div>
        <div class="line-content">This is Page 26 content example with next and prev.</div>
        <div class="line-content">This is Page 27 content example with next and prev.</div>
        <div class="line-content">This is Page 28 content example with next and prev.</div>
        <div class="line-content">This is Page 29 content example with next and prev.</div>
        <div class="line-content">This is Page 30 content example with next and prev.</div>
        <div class="line-content">This is Page 31 content example with next and prev.</div>
        <div class="line-content">This is Page 32 content example with next and prev.</div>
        <div class="line-content">This is Page 33 content example with next and prev.</div>
        <div class="line-content">This is Page 34 content example with next and prev.</div>
        <div class="line-content">This is Page 35 content example with next and prev.</div>
        <div class="line-content">This is Page 36 content example with next and prev.</div>
        <div class="line-content">This is Page 37 content example with next and prev.</div>
        <div class="line-content">This is Page 38 content example with next and prev.</div>
        <div class="line-content">This is Page 39 content example with next and prev.</div>
        <div class="line-content">This is Page 40 content example with next and prev.</div>
        <div class="line-content">This is Page 41 content example with next and prev.</div>
        <div class="line-content">This is Page 42 content example with next and prev.</div>
        <div class="line-content">This is Page 43 content example with next and prev.</div>
        <div class="line-content">This is Page 44 content example with next and prev.</div>
        <div class="line-content">This is Page 45 content example with next and prev.</div>
        <ul id="pagin"></ul>
    </body>
</html>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script>

pageSize = 5;
incremSlide = 5;
startPage = 0;
numberPage = 0;

var pageCount =  $(".line-content").length / pageSize;
var totalSlidepPage = Math.floor(pageCount / incremSlide);
    
for(var i = 0 ; i<pageCount;i++){
    $("#pagin").append('<li><a href="#">'+(i+1)+'</a></li> ');
    if(i>pageSize){
       $("#pagin li").eq(i).hide();
    }
}

var prev = $("<li/>").addClass("prev").html("Prev").click(function(){
    startPage-=5;
    incremSlide-=5;
    numberPage--;
    slide();
});

prev.hide();

var next = $("<li/>").addClass("next").html("Next").click(function(){
    startPage+=5;
    incremSlide+=5;
    numberPage++;
    slide();
});

$("#pagin").prepend(prev).append(next);

$("#pagin li").first().find("a").addClass("current");

slide = function(sens){
    $("#pagin li").hide();
   
    for(t=startPage;t<incremSlide;t++){
        $("#pagin li").eq(t+1).show();
    }
    if(startPage == 0){
        next.show();
        prev.hide();
    }else if(numberPage == totalSlidepPage ){
        next.hide();
        prev.show();
    }else{
        next.show();
        prev.show();
    }    
}

showPage = function(page) {
    $(".line-content").hide();
    $(".line-content").each(function(n) {
        if (n >= pageSize * (page - 1) && n < pageSize * page){
            $(this).show();
        }
    });        
}
    
showPage(1);
$("#pagin li a").eq(0).addClass("current");

$("#pagin li a").click(function() {
    $("#pagin li a").removeClass("current");
    $(this).addClass("current");
    showPage(parseInt($(this).text()));
});
</script>

Output:

how_to_create_pagination_using_jquery_output

Example:

In this example, we will create bootstrap pagination with help of jquery.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>How To Create Bootstrap Pagination Using jQuery - Websolutionstuff</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
        <style>
            #data tr {
                display: none;
            }

            .page {
                margin: 30px;
            }

            table, th, td {
                border: 1px solid black;
            }

            #data {
                font-family: Arial, Helvetica, sans-serif;
                border-collapse: collapse;
                width: 100%;
            }

            #data td, #data th {
                border: 1px solid #ddd;
                padding: 8px;
            }

            #data tr:nth-child(even) {
                background-color: #f2f2f2;
            }

            #data tr:hover {
                background-color: #ddd;
            }

            #data th {
                padding-top: 12px;
                padding-bottom: 12px;
                text-align: left;
                background-color: #03aa96;
                color: white;
            }

            #nav a {
                color: #03aa96;
                font-size: 20px;
                margin-top: 22px;
                font-weight: 600;
            }

            a:hover, a:visited, a:link, a:active {
                text-decoration: none;
            }

            #nav {
                margin-top: 20px;
            }
        </style>
    </head>
    <body>                  
        <h2 align="center" class="mt-4">How To Create Bootstrap Pagination Using jQuery - Websolutionstuff</h2>
        <div class="page" align="center">   
            <table id="data">  
                <tr>  
                    <th>Id</th>  
                    <th>Name</th>  
                    <th>Country</th>  
                </tr>  
                <tr>  
                    <td>1</td>  
                    <td>Maria</td>  
                    <td>Germany</td>  
                </tr>  
                <tr>  
                    <td>2</td>  
                    <td>Christina</td>  
                    <td>Sweden</td>  
                </tr>  
                <tr>  
                    <td>3</td>  
                    <td>Chang</td>  
                    <td>Mexico</td>  
                </tr>  
                <tr>  
                    <td>4</td>  
                    <td>Mendel</td>  
                    <td>Austria</td>  
                </tr>  
                <tr>  
                    <td>5</td>  
                    <td>Helen</td>  
                    <td>United Kingdom</td>  
                </tr>  
                <tr>  
                    <td>6</td>  
                    <td>Philip</td>  
                    <td>Germany</td>  
                </tr>  
                <tr>  
                    <td>7</td>  
                    <td>Tannamuri</td>  
                    <td>Canada</td>  
                </tr>  
                <tr>  
                    <td>8</td>  
                    <td>Rovelli</td>  
                    <td>Italy</td>  
                </tr>  
                <tr>  
                    <td>9</td>  
                    <td>Dell</td>
                    <td>United Kingdom</td>
                </tr>  
                <tr>  
                    <td>10</td>  
                    <td>Trump</td>  
                    <td>France</td>  
                </tr>  
            </table>  
        </div>
    </body>
</html>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script>
$(document).ready (function () {  
    $('#data').after ('<div id="nav"></div>');  
    var rowsShown = 5;  
    var rowsTotal = $('#data tbody tr').length;  
    var numPages = rowsTotal/rowsShown;  
    for (i = 0;i < numPages;i++) {  
        var pageNum = i + 1;  
        $('#nav').append ('<a href="#" rel="'+i+'">'+pageNum+'</a> ');  
    }  
    $('#data tbody tr').hide();  
    $('#data tbody tr').slice (0, rowsShown).show();  
    $('#nav a:first').addClass('active');  
    $('#nav a').bind('click', function() {  
    $('#nav a').removeClass('active');  
    $(this).addClass('active');  
        var currPage = $(this).attr('rel');  
        var startItem = currPage * rowsShown;  
        var endItem = startItem + rowsShown;  
        $('#data tbody tr').css('opacity','0.0').hide().slice(startItem, endItem).  
        css('display','table-row').animate({opacity:1}, 300);  
    });  
});
</script>

Output:

how_to_create_pagination_using_jquery_and_bootstrap

Example:

In this example, we will create pagination using the twbsPagination plugin. This jQuery plugin simplifies the usage of Bootstrap Pagination.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>jQuery Pagination Using Plugin - Websolutionstuff</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
        <style>
            .wrapper{
                margin: 60px auto;
                text-align: center;
            }
            h2{
                margin-bottom: 1.25em;
            }
            
            #pagination-demo{
                display: inline-block;
                margin-bottom: 1.75em;
            }

            #pagination-demo li{
                display: inline-block;
            }

            .page-content{
                background: #eee;
                display: inline-block;
                padding: 10px;
                width: 100%;
                max-width: 660px;
            }
        </style>
    </head>
    <body>                  
        <div class="wrapper">
            <div class="container">
              
              <div class="row">
                <div class="col-sm-12">
                  <h2>jQuery Pagination Using Plugin - Websolutionstuff</h2>
                  <p>Simple pagination using the TWBS pagination JS library.</p>
                  <ul id="pagination-demo" class="pagination-sm"></ul>
                </div>
              </div>
          
              <div id="page-content" class="page-content">Page 1</div>
            </div>
          </div>
    </body>
</html>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twbs-pagination/1.4.1/jquery.twbsPagination.min.js"></script>
<script>
$(document).ready (function () {  
    $('#pagination-demo').twbsPagination({
        totalPages: 16,
        visiblePages: 6,
        next: 'Next',
        prev: 'Prev',
        onPageClick: function (event, page) {            
            $('#page-content').text('Page ' + page) + ' content here';
        }
    });
});
</script>

Output:

jquery_pagination_using_plugin

Original article source at: https://websolutionstuff.com/

#jquery #pagination