Search the Blog

Showing posts with label Matplotlib. Show all posts
Showing posts with label Matplotlib. Show all posts

Sunday, October 6, 2019

Linear Programming Problem (LPP) Learnig Example with more than 2 varibles For Data Science Biggner in Python and Jupyter

In this Post we will learn lot of Linear Programming Problem Example. I will try to provide the coding part of problem not the lengthy documentation.

Now lets Start with our Examples which is generally asked in various unveristy exams also.


Example 1:-

A Manufacturing compamy is engaged in producing three types of product L, M and  N. The production department produces, each day, components sufficent to make 50 units of L, 25 Units of M and 30 units of N.
The management is confronted with the problem of optimizing the daily production of the prodccts in the assembly department, where only 100 man hours are availble daily for assembly the products.

Following addtional information is available-

Type of Product Profit Contribution per Unit of Products (RS.) Assemble Time per product (hrs)
L 12 0.8
M 20 1.7
N 45 2.5

The Company has a daily order commitment for 20 units of product L  and a total of 15 units of M and N.

Now we have to Formulate the  Linear programming model as maximize the total profit.

Now LP Model formulation of the is problem is -

Constraints   Product Type  Total
L M N
Production Capacity 50 25 30
Man Hours per Unit 0.8 1.7 2.5 100
Order commitment  20 15( both of M and N)
Profit Contribution 12 20 45


Maximize Or Objective Function above Problem is -  

     Z=12 X1 + 20 X2 + 45 X3 or 
    Z=12x+20y+24z


Comstraints-
   (A) 0.8X1 + 1.7X2 +2.5 X3 <=100
   (B) X1 <= 50
   (C) X2 <= 25
   (D) X3 <= 30

ORDER COMMITMENT
  (A) X1 >= 20
  (B) X2 + X3 >=15
  (C) X1, X2, X3 >=0

This is the Complete description of our Problem, Now lets start the coding in python to get the final output of problem.

Solution -
As per our profit contribution we should have minimum production of product L, then M and maximum of N.
Now we have to find the coordinates.
1- X1=(0,20) and (0,50)
2- X2= (0,15)
3- X3= (0,15)







Sunday, September 29, 2019

Data Analysis of Purchase Order of an Organization with AI

In this post, I will explain the  Python data Analysis Concept with AI Question with Live Data and Code and Data.

Topic Main Points


 1- Python
 2- Pandas
 3- Numpy
 4- MatplotLib
 5- PO of Industrial Organization.
 6- AI of Industrial Purchase Question of a perticular Session.

Now lets Start, I will explain the AI Question which could be raised against a perticular data set  PO against a perticular session.
  
I tried top explain  all the Topics Sequenctillay, what i bignner Data Scientiest need to know.

Step 1:- Creating the first Data Frame of  Main PO Details 

# query Master Reading



Pur_order_mast = "SELECT  
                               URN_NO,                                                                  convert(nvarchar,pur_order_date,103)as Date,
 Pur_Order_No as [Order_No],
supp_code as [Sup_Code] 
from purchase_order_mast  
where (PO_Status='Approved' or PO_Status='Not Approved')  
and co_code like '%a%'" 

Pur_df_1 = pd.read_sql(Pur_order_mast, conn)


# Testing of Data

Pur_df_1.head(5)
Step 2:- Create Second Data Frame for PO Details Part

# Query for Details Reading
Pur_order_det = "SELECT URN_NO,it_code,alt_qty as [Item_qty],alt_rate as Rate from purchase_order_det  where (PO_Status='Approved' or PO_Status='Not Approved')and co_code like '%a%'" 

Pur_df_2 = pd.read_sql(Pur_order_det, conn)

# Testing of Data
Pur_df_2.head(5)

Create Second Data Frame for PO Details Part Data Science

Step 3:- Create Third Data Frame of Itemmaster

# Query for Itemmaster Reading
Itemmaster = "SELECT it_code,alt_name as [Item_Name] from itemmaster  where (item_Status='Approved' or item_Status='Not Approved')and co_code like '%a%'" 
Itemmaster = pd.read_sql(Itemmaster, conn)


Create Third Data Frame of Itemmaster Data Science

Step 4:- Create Fourth Data Frame of Supplier Master
# Query for Itemmaster Reading
AccountMaster = "SELECT Sr_no,ac_name from acct_mast  where (acc_Status='Approved' or acc_Status='Not Approved')and co_code like '%a%'" 
AccountMaster = pd.read_sql(AccountMaster, conn)

#Testing of DATA
AccountMaster.head(5)

Create Fourth Data Frame of Supplier Master Data Science

Step 5:- Merging of all dataframe object into single Data Frame


# Merging of data Sequentially and  Making a useful data
# First we will create master Data Frame of from the available 
# dataframe objects
# first we will merge details and master part
Final_order_details = pd.merge(Pur_df_2,Pur_df_1)

# Purchase order main data and Purchase order details data merging
Final_order_details.head(5)
Pandas Merging of all dataframe object into single Data Frame

# Now we will merge the data of accounts name to the current frame

Final_order_details = pd.merge(Final_order_details,AccountMaster, left_on ='Sup_Code', right_on='Sr_no')

# Now we will merge the item name to the data set

Final_order_details = pd.merge(Final_order_details,Itemmaster, on ='it_code')

Final_order_details.head(5)

Step 6:- Function to remove duplicate rows 

# function to remove duplicates key from a DataFrame 
def getDuplicateColumns(df):
    '''
    Get a list of duplicate columns.
    It will iterate over all the columns in dataframe and find the columns whose content are duplicate.
    :param df: Dataframe object
    :return: List of columns whose contents are duplicates.
    '''
    duplicateColumnNames = set()
    # Iterate over all the column in DataFrame
    for x in range(df.shape[1]):
        # Select column at xth index.
        col = df.iloc[:, x]
        # Iterate over all the columns in DataFrame from (x+1)th index till end
        for y in range(x + 1, df.shape[1]):
            # Select column at yth index.
            otherCol = df.iloc[:, y]
            # Check if two columns at x 7 y index are equal
            if col.equals(otherCol):
                duplicateColumnNames.add(df.columns.values[y])
    return list(duplicateColumnNames)


#Final_order_details.drop (["it_code","Sup_Code","Sr_no","Item_Name_x"], axis = 1)
Final_order_details = Final_order_details.drop
(columns=getDuplicateColumns(Final_order_details))


# Finally print the Usable DataFrame and Test 
#and check that only useful data is ready for anylysis.
Final_order_details.head(2)
Finally print the Usable DataFrame and Test  Data Science


Now from the available data we have to answer the following Question

# Question 1:- What is the Monthely Costing on Purchase.


Complete Code 

# parameters
import pandas as pd
import pyodbc
from pandas import Series

DB = {'servername': '103.27.100.100',
      'database': 'dizsweb'
     }
# create the connection
conn = pyodbc.connect('DRIVER={SQL Server};
SERVER=' + DB['servername'] + ';
DATABASE=' + DB['database'] + ';
UID= dizsweb;PWD= dizsweb
;Trusted_Connection=no')

# function to remove duplicates key from a DataFrame
def getDuplicateColumns(df):
    '''
    Get a list of duplicate columns.
    It will iterate over all the columns in dataframe and find the columns whose content are duplicate.
    :param df: Dataframe object
    :return: List of columns whose contents are duplicates.
    '''
    duplicateColumnNames = set()
    for x in range(df.shape[1]):
        # Select column at xth index.
        col = df.iloc[:, x]
        # Iterate over all the columns in DataFrame from (x+1)th index till end
        for y in range(x + 1, df.shape[1]):
            otherCol = df.iloc[:, y]
            if col.equals(otherCol):
                duplicateColumnNames.add(df.columns.values[y])
    return list(duplicateColumnNames)
Pur_order_mast = "SELECT URN_NO,pur_order_date as Date,Pur_Order_No as [Order_No],supp_code as [Sup_Code] from purchase_order_mast  where (PO_Status='Approved' or PO_Status='Not Approved')  and co_code like '%a%'"
Pur_df_1 = pd.read_sql(Pur_order_mast, conn)
Pur_df_1.head(5)
Pur_order_det = "SELECT URN_NO,it_code,alt_qty as [Item_qty],alt_rate as Rate from purchase_order_det  where (PO_Status='Approved' or PO_Status='Not Approved')and co_code like '%a%'"
Pur_df_2 = pd.read_sql(Pur_order_det, conn)
Pur_df_2.head(5)
Itemmaster = "SELECT it_code,alt_name as [Item_Name] from itemmaster  where (item_Status='Approved' or item_Status='Not Approved')and co_code like '%a%'"
Itemmaster = pd.read_sql(Itemmaster, conn)
Itemmaster.head(5)
AccountMaster = "SELECT Sr_no,ac_name from acct_mast  where (acc_Status='Approved' or acc_Status='Not Approved')and co_code like '%a%'"
AccountMaster = pd.read_sql(AccountMaster, conn)
Final_order_details = pd.merge(Pur_df_2,Pur_df_1)
Final_order_details.head(5)
Final_order_details = pd.merge(Final_order_details,AccountMaster, left_on ='Sup_Code', right_on='Sr_no')
Final_order_details = pd.merge(Final_order_details,Itemmaster, on ='it_code')
Final_order_details['Amount'] =  Final_order_details['Item_qty']* Final_order_details['Rate']
Final_order_details.head(5)
#Final_order_details.drop(["it_code","Sup_Code","Sr_no","Item_Name_x"], axis = 1)
Final_order_details = Final_order_details.drop(columns=getDuplicateColumns(Final_order_details))
Final_order_details.head(5)
Final_order_details.head(5)
Final_order_details.head(2)
Monthely_purchase_costing = Final_order_details[['Date','Amount']]
Monthely_purchase_costing.info()
Monthely_purchase_costing['Date'] = pd.to_datetime(Monthely_purchase_costing['Date'],format='%y-%m-%d')
Monthely_purchase_costing.head(8)
Monthely_purchase_costing.info()
Monthely_purchase_costing2 = Monthely_purchase_costing.groupby([pd.Grouper(key='Date', freq='M')]).agg({'Amount':sum})
Monthely_purchase_costing2
Monthely_purchase_costing2.info()
Monthely_purchase_costing["Year"],Monthely_purchase_costing["Month"],Monthely_purchase_costing["Day"] = Monthely_purchase_costing.Date.dt.year,Monthely_purchase_costing.Date.dt.month,Monthely_purchase_costing.Date.dt.day
Monthely_purchase_costing_OK=Monthely_purchase_costing
Monthely_purchase_costing_OK
Month_costing = Monthely_purchase_costing_OK.groupby(['Month']).sum()
import matplotlib.dates as dates
%matplotlib inline
df=pd.DataFrame(
    { 'x': Month_costing1.index,
     'y1': Month_costing1.Amount
    })


plt.plot( 'x', 'y1', data=df, marker='o', markerfacecolor='blue', markersize=1, color='skyblue', linewidth=1)
plt.legend()



Sunday, September 15, 2019

Data Science Sample example for Beginner

Data Science Complete  Example with Library Pandas and Matplotlib :-

Sample Data Frame for Data Analysis in juypter with library pandas matplotlib

Learning of data Science is very easy for developer  and IT backgroud people beacuse they knows about programming mathodolgy and syntax in various other language. As java have its own set of rules for execute the program in the same way python have its own.

In this post i will explain about the code regarding to plot the data of company for april 1st week sales graph. To demonstrate that i have designed my own data set and save that data in CSV File.

Basic requirement to run this program and code are following

1- Python
2- Juypter Notebook
3- pandas 
4- matplotlib
5- dataset (In my case it is CSV File)

Python 

 I have installed Python 3.7. If you are new please download that first.


Note:- Download the python from anaconda site and download distribution version, Because with distribution version all required library will be installed, User don't need to download that separately.


To Check python is installed correctly please open cmd and run the following command.

C:\Users\HP>python
python insatllation testing

When you run the command then it will show you the currently installed version of python in your system.


Opening of Jupyter Notebook

Open the CMD and run the following command

C:\Users\HP>jupyter notebook

jupyter notenook opening via cmd prompt

Now the Screen will look Like This

Jupyter userr interface

Now The Complete Code is-
Step 1:- Defining of Pandas Lib, Numpy Lib
Defining of Pandas Lib, Numpy Lib

Step 2:- Reading the CSV File. In this Case i have the location of                  CSV File is same as of my jupyter directory
Reading the CSV File python pandas


Step 3:- Defining the Name of Columns
Defining the Name of Columns

Step 4:- Printing of read data.
Printing of read data pandas matplotlib python

Step 5:- Definng of matplotlib 
Step 6:- Creating the plot parameter 
Creating the plot parameter

Step 7:- Running of Final Code.

Translate