Thursday, October 25, 2018

Django - Start Guide

Django's primary goal is to ease the creation of complex, database-driven websites. Django emphasizes reusability and "pluggability" of components, less code, low coupling, rapid development, and the principle of don't repeat yourself.

Python is used throughout, even for settings files and data models. Django also provides an optional administrative create, read, update and delete interface that is generated dynamically through introspection and configured via admin models. 


In this below section we will learn to start basic server based website.

1.Install Virtual environment & Django:
   
  Go to command prompt and run pip install virtualenv  to install virtual environment 
  after that run pip install django  to finally install Django.

 
2. Create Folder : lets create a folder name Django Pro under which we need to run command prompt to tun pip freeze command to check the version of Django

C:\Django Pro>pip freeze
beautifulsoup4==4.6.0
Django==2.1.2
get==1.0.0
post==1.0.0
public==1.0.0
pytz==2018.5
query-string==1.0.0
request==1.0.0
selenium==3.11.0
virtualenv==16.0.0



3.Run Django: Now run following command to create sub directories under Django pro folder
   C:\Django Pro>django-admin.py startproject trydjango18

 now you will be able to see all new folder created by above command .

C:\Django Pro>dir
 Volume in drive C has no label.
 Volume Serial Number is 2E8B-D19A

 Directory of C:\Django Pro

10/20/2018  05:09 PM    <DIR>          .
10/20/2018  05:09 PM    <DIR>          ..
04/07/2018  05:58 PM    <DIR>          Include
10/20/2018  05:04 PM    <DIR>          Lib
10/20/2018  05:05 PM                59 pip-selfcheck.json
10/20/2018  05:05 PM    <DIR>          Scripts
10/20/2018  05:04 PM    <DIR>          tcl
10/20/2018  05:09 PM    <DIR>          Src
               1 File(s)             59 bytes
               7 Dir(s)  43,012,898,816 bytes free



4. Run manage.py  : Just to Src ( name folder in my case)  and  run 

    C:\Django Pro\src>python manage.py

5. Run server: In order to do so just run below command on terminal /cmd prompt

  C:\Django Pro\src>python manage.py runserver

You will get :

C:\Django Pro\src>python manage.py runserver
Performing system checks...


System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
October 20, 2018 - 17:10:55
Django version 2.1.2, using settings 'trydjango18.settings'
Starting development server at http://127.0.0.1:8000/    ------> Your Django ip address
Quit the server with CTRL-BREAK.
[20/Oct/2018 17:11:09] "GET / HTTP/1.1" 200 16348
[20/Oct/2018 17:11:09] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[20/Oct/2018 17:11:09] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304
[20/Oct/2018 17:11:09] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348
[20/Oct/2018 17:11:09] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564
Not Found: /favicon.ico
[20/Oct/2018 17:11:09] "GET /favicon.ico HTTP/1.1" 404 1977



  6. Admin Web Access : Just enter above IP address on your browser.


Congratulations you are on Django first web interface.



Monday, October 22, 2018

Load and Display Data (Excel , text or CSV) in Python with Gui form.

In this section we will be creating a dialog based gui to load data from EXCEL or CSV  and display the information on same view.


Lib Requirement: Tikinter

Code:

try:
    # Python 2
    import Tkinter as tk
    import ttk
    from tkFileDialog import askopenfilename
except ImportError:
    # Python 3
    import tkinter as tk
    from tkinter import ttk
    from tkinter.filedialog import askopenfilename

import pandas as pd

# --- classes ---

class MyWindow:

    def __init__(self, parent):

        self.parent = parent

        self.filename = None
        self.df = None

        self.text = tk.Text(self.parent)
        self.text.pack()

        self.button = tk.Button(self.parent, text='LOAD DATA', command=self.load)
        self.button.pack()

        self.button = tk.Button(self.parent, text='DISPLAY DATA', command=self.display)
        self.button.pack()

    def load(self):

        name = askopenfilename(filetypes=[('CSV', '*.csv',), ('Excel', ('*.xls', '*.xlsx'))])

        if name:
            if name.endswith('.csv'):
                self.df = pd.read_csv(name)
            else:
                self.df = pd.read_excel(name)

            self.filename = name

            # display directly
            #self.text.insert('end', str(self.df.head()) + '\n')

    def display(self):
        # ask for file if not loaded yet
        if self.df is None:
            self.load()

        # display if loaded
        if self.df is not None:
            self.text.insert('end', self.filename + '\n')
            self.text.insert('end', str(self.df) + '\n')


# --- main ---

if __name__ == '__main__':
    root = tk.Tk()
    top = MyWindow(root)
    root.mainloop()



Output:
 Form:

 Select the format:
 Select the file:
 Click on Display Data:


Thursday, October 18, 2018

How to Read Excel in Python using Pandas

Nowadays the very first python interview question asked by the company is "How to read data from Excel"

In the below example we have an simple example to read the data from excel and show in python.


First, we need to have an excel sheet , in  my case i have below one stored in c:/test/ location


Second, Now we just need Pandas lib to read all data into data frame for which we have code as below.

# importing Panda library and using as 'pd'

import pandas as pd 

#reading excel sheet in data frame in python

df=pd.read_excel("C:\\test\\Data.xlsx")

#Displaying data set 'Top 5 row

df.head()


Output



Wednesday, October 17, 2018

Screen Monitoring / Task monitoring on Winodows 10/8/7

In this below code execution you will be able to record every step on window.

 

Language: Python

Lib: Win32 , OS, Tikinter, datetime, time  & Openpyxl




import win32gui
import time
import datetime
import openpyxl
import os
import tkinter as tk
from tkinter import *
w=win32gui
from openpyxl import Workbook
print("\t Copyright Reserved: @Rohit Kankhedia #.com   \n\n \t\t india \n\t This window will autoclose after 30 sec session \n\t your resule will be exported in C:/te/")
home_dir = ('C:\Te')       
if not os.path.isdir(home_dir):
    os.makedirs(home_dir)
    #print("Home directory %s was created." %home_dir)
book = Workbook()
sheet = book.active
value_1=[]
value_2=[]
val=str(w.GetWindowText (w.GetForegroundWindow()))
sheet["B1"].value="Task"
sheet["C1"].value="Time"
sheet["D1"].value="DateTime_IF_Change"
sheet["E1"].value="Time_IF_Change"
sheet["F1"].value="Time_Spent on Task"
def Start1():
        #counter_label(label)               
        for i in range(2, 30):
            time.sleep(1)
            #if str(w.GetWindowText (w.GetForegroundWindow()))!=NewTask[i]:
             #   NewTask[i]=str(w.GetWindowText (w.GetForegroundWindow()))
              #  NewTime[i]=datetime.datetime.now()
            value_1.append(str(w.GetWindowText (w.GetForegroundWindow())))
            value_2.append(datetime.datetime.now())
           
            #OldTime[i]=datetime.datetime.now()
            #print(str(w.GetWindowText (w.GetForegroundWindow())),datetime.datetime.now())
       
        for i in range(2,28):
            print(value_1[i],value_2[i])
            if i==2 or i==27:
                sheet["D"+str(i)].value=value_2[i]
               
                sheet["E"+str(i)].value='=HOUR(D{0})&":"&MINUTE(D{0})&":"&SECOND(D{0})'.format(i)
                if i!=2 :
                  sheet["F"+str(i)].value=value_2[i]-temp1
                temp1=value_2[i]
            if value_1[i]!=value_1[i-1]:
                #temp=value_1[i]
                sheet["D"+str(i)].value=value_2[i]
                sheet["E"+str(i)].value='=HOUR(D{0})&":"&MINUTE(D{0})&":"&SECOND(D{0})'.format(i)
                sheet["F"+str(i)].value=value_2[i]-temp1
                temp1=value_2[i]
               
           
            sheet["B"+str(i)].value=value_1[i]
            sheet["C"+str(i)].value=str(value_2[i])
           
        book.save("c:\\Te\\Track_R.xlsx")
        root.destroy()
      
root = tk.Tk()
root.title('Time-12-Track')
time1 = ''
clock = Label(root, font=('times', 20, 'bold'), bg='green')
clock.pack(fill=BOTH, expand=1)
def tick():
    global time1
    # get the current local time from the PC
    time2 = time.strftime('%H:%M:%S')
    # if time string has changed, update it
    if time2 != time1:
        time1 = time2
        clock.config(text=time2)
    # calls itself every 200 milliseconds
    # to update the time display as needed
   # could use >200 ms, but display gets jerky
    clock.after(200, tick)
tick()
tk.Label(root,
   text="\t Copyright Reserved: @Rohit Kankhedia #BT.com   \n\n\t BT india \n\t This window will autoclose after 30 sec session \n\t your resule will be exported in C:/te/",
   fg = "red",
   font = "Times").pack()
button = tk.Button(root, text='Start', width=25, command=Start1)
button.pack()
counter = 0
button1 = tk.Button(root, text='Stop', width=25, command=root.destroy)
button1.pack()


root.mainloop()


Tool Screen:

 

Wednesday, October 10, 2018

Explained: How skilling can offset automation threat

If skilling is scaled up, we would be able to adapt to any and all changes


Sitakanta Panda

AI, robotics and Big Data are the facets of the digital revolution in which automation is the central theme. There are many aspects to the phenomenon, which most people perceive as a problem. When seen as a problem, there are many aspects to it too. For instance, on social media platforms like Twitter, “bots” are used to inflate the numbers of followers of celebrities or politicians, and also for trolling. Automation and digital revolution has led to anxiety for its disruptive possibilities, including on the future human labour.
Automation in manufacturing and services sectors in G20 (and other developed) countries has increased a lot, as self-optimising, self-correcting machines are substituting human labour. These machines with fed-in algorithms are doing the work that comprises not just repetitive tasks but also cognitive tasks involving subtle and non-routine judgement. Carl Frey and Michael Osborne in a famous 2017 study “The future of employment: How susceptible are jobs to computerisation?” classify 702 occupations on their susceptibility to automation. They conclude that over the next two decades 47% of the US workers are at risk of automation. According to World Bank estimates stated in the 2016 World Development Report, 57% of jobs in OECD countries could be automated over the next two decades.

The composition of the employment structure is changing and the share of labour in overall income is declining in the developed world. Yiqun Gloria Chen in a 2016 study found that employment and income shares of routine-intensive occupations have declined significantly relative to non-routine occupations. Wage and income inequalities are widening as the gap between the returns to labour and returns to capital is rising.
On the other hand, benefits of automation are appealing to producers—greater penetration of robots has reduced production costs and, consequently, wages and employment decline because of displacement effects (displacing workers from tasks) and a spurt in the productivity effect (as other industries and/or tasks increase their demand for labour).
In their 2017 study “Robots and jobs: Evidence from US labor markets”, Daron Acemoglu and Pascual Restrepo find that introduction of one more robot per 1,000 workers reduces employment-to-population ratio by 0.18 to 0.34 percentage points and wages by 0.25-0.5%. Digital revolution has created completely new jobs and industries (web designer, software developer, data security expert), though these demand high-skilled labour.

Societies that are able to offset the negative effects of increasing automation and digital technologies that replace humans would stand to gain the most in terms of sustainable economic progress. Aggregate societal welfare would increase upon rapid tech advances that effectively substitute cheap and abundant capital for previously expensive and wilful labour. But economists like David Autor opine that eking out a living for those who own labour but do not own capital would be more difficult. Thus, the distributional effects of increasing automation are worrisome.

A few salient narratives characterise how global labour markets are responding to the current technological change. First, according to a 2010 study by Autor, in an ongoing phenomenon called ‘job polarisation’, the highest and lowest ends of the skills spectrum have seen the most robust employment growth and two distinct sets of workforce have emerged—one with high-skilled, high-wage jobs, and the other with low-skilled, low-wage jobs.
The jobs that need middle-level skills, in contrast, contain highest concentration of routine tasks and are relatively easy to automate and run the risk of disappearance. Second, tech progress has enabled machines to do manual tasks that are more complex and non-routine—self-driving cars could possibly replace jobs in the trucking and logistics industry and Big Data and machine learning algorithms have the potential of replacing service occupations like administrative and clerical office staff.

Two competing effects of such tech progress are at work: technology replaces human labour requiring workers to reallocate their labour elsewhere, and it increases demand for other goods and services as new digital economy jobs and industries are created.
The extent to which tech will substitute or complement human labour depends on the tasks automation will take over and whether it can perform them with a comparable level of skill.
Studies show that sufficiently complex tasks require advanced skills that current automation technologies cannot perform. As increased digitalisation coincides with changes in the work environment and tasks expected to be carried out by workers, certain skills will be obsolete and new skills will find demand. The magnitude will vary by occupations and sectors.
In some sectors, new skill-sets will supplement and not supplant existing skill-sets—many future jobs will be defined by workers’ ability to analyse and work with data, and make data-based decisions. With future prevalence of automation and AI, a number of tasks involving technical skills like troubleshooting machine problems and resource management skills would be eliminated over time. But the demand for essentially human jobs (such as technicians with skills for repairing and maintenance) will increase.

Studies indicate that different countries will experience the labour market impact of automation differently. Developed countries use more technology at work and are experiencing faster changes in skill requirements, so their labour markets could witness larger disruptions in the near future. Out there, a smaller share of the workforce is employed in routine occupations susceptible to automation, but higher wages for human labour make automation a rational option.
Developing and low-income countries have a large number of workers in routine occupations. As these economies adopt automation faster, their labour markets will be substantially affected, albeit with a time lag. But labour markets in less developed countries suffer from huge skill deficit and this will exacerbate the problem of labour-capital and labour-machine conflicts.
To address labour market challenges, economists have mooted solutions such as skilling and training, taxation policies, social safety nets. Promoting faster skill development of the workforce is a policy priority since the higher the skill level of a job, the less likely it is for a machine to replace a human. Matthias Oschinski and Rosalie Wyonch in a 2017 study find that occupations high in abstract, complex decision-making skills with a strong focus on creativity and ideas, critical thinking and interpersonal social skills are at low risk of being automated.

Jobs that involve human interaction, heuristics of communication, persuasion and negotiation (like management, business and finance), along with jobs that require coming up with novel ideas and creativity (like those in the arts, media, engineering and science), are relatively safer jobs.
As India has abundant labour segregated in the informal sector that thrive on low-skill, low-wage jobs and occupations and a paucity of skilled labour, adoption of automation in the near future is expected to be sluggish despite huge presence of ICT-enabled industries and services in some pockets. The 2017 World Robotics Report states that India purchased 2,627 industrial robots in 2016 (comprising just 0.89% of global shipment). But the looming prospect of rising automation in manufacturing and services sectors offers a big opportunity for India, especially for skilling workforce. If skilling is scaled up, we would be able to adapt to the change.

Tuesday, October 9, 2018

The Basics of NumPy Arrays

Data manipulation in Python is nearly synonymous with NumPy array manipulation: even newer tools like Pandas (Chapter 3) are built around the NumPy array. This section will present several examples of using NumPy array manipulation to access data and subarrays, and to split, reshape, and join the arrays. While the types of operations shown here may seem a bit dry and pedantic, they comprise the building blocks of many other examples used throughout the book. Get to know them well!
We'll cover a few categories of basic array manipulations here:
  • Attributes of arrays: Determining the size, shape, memory consumption, and data types of arrays
  • Indexing of arrays: Getting and setting the value of individual array elements
  • Slicing of arrays: Getting and setting smaller subarrays within a larger array
  • Reshaping of arrays: Changing the shape of a given array
  • Joining and splitting of arrays: Combining multiple arrays into one, and splitting one array into many

NumPy Array Attributes

First let's discuss some useful array attributes. We'll start by defining three random arrays, a one-dimensional, two-dimensional, and three-dimensional array. We'll use NumPy's random number generator, which we will seed with a set value in order to ensure that the same random arrays are generated each time this code is run:
In [1]:
import numpy as np
np.random.seed(0)  # seed for reproducibility

x1 = np.random.randint(10, size=6)  # One-dimensional array
x2 = np.random.randint(10, size=(3, 4))  # Two-dimensional array
x3 = np.random.randint(10, size=(3, 4, 5))  # Three-dimensional array
Each array has attributes ndim (the number of dimensions), shape (the size of each dimension), and size (the total size of the array):
In [2]:
print("x3 ndim: ", x3.ndim)
print("x3 shape:", x3.shape)
print("x3 size: ", x3.size)
x3 ndim:  3
x3 shape: (3, 4, 5)
x3 size:  60
Another useful attribute is the dtype, the data type of the array (which we discussed previously in Understanding Data Types in Python):
In [3]:
print("dtype:", x3.dtype)
dtype: int64
Other attributes include itemsize, which lists the size (in bytes) of each array element, and nbytes, which lists the total size (in bytes) of the array:
In [4]:
print("itemsize:", x3.itemsize, "bytes")
print("nbytes:", x3.nbytes, "bytes")
itemsize: 8 bytes
nbytes: 480 bytes
In general, we expect that nbytes is equal to itemsize times size.

Array Indexing: Accessing Single Elements

If you are familiar with Python's standard list indexing, indexing in NumPy will feel quite familiar. In a one-dimensional array, the ith value (counting from zero) can be accessed by specifying the desired index in square brackets, just as with Python lists:
In [5]:
x1
Out[5]:
array([5, 0, 3, 3, 7, 9])
In [6]:
x1[0]
Out[6]:
5
In [7]:
x1[4]
Out[7]:
7
To index from the end of the array, you can use negative indices:
In [8]:
x1[-1]
Out[8]:
9
In [9]:
x1[-2]
Out[9]:
7
In a multi-dimensional array, items can be accessed using a comma-separated tuple of indices:
In [10]:
x2
Out[10]:
array([[3, 5, 2, 4],
       [7, 6, 8, 8],
       [1, 6, 7, 7]])
In [11]:
x2[0, 0]
Out[11]:
3
In [12]:
x2[2, 0]
Out[12]:
1
In [13]:
x2[2, -1]
Out[13]:
7
Values can also be modified using any of the above index notation:
In [14]:
x2[0, 0] = 12
x2
Out[14]:
array([[12,  5,  2,  4],
       [ 7,  6,  8,  8],
       [ 1,  6,  7,  7]])
Keep in mind that, unlike Python lists, NumPy arrays have a fixed type. This means, for example, that if you attempt to insert a floating-point value to an integer array, the value will be silently truncated. Don't be caught unaware by this behavior!
In [15]:
x1[0] = 3.14159  # this will be truncated!
x1
Out[15]:
array([3, 0, 3, 3, 7, 9])

Array Slicing: Accessing Subarrays

Just as we can use square brackets to access individual array elements, we can also use them to access subarrays with the slice notation, marked by the colon (:) character. The NumPy slicing syntax follows that of the standard Python list; to access a slice of an array x, use this:
x[start:stop:step]
If any of these are unspecified, they default to the values start=0, stop=size of dimension, step=1. We'll take a look at accessing sub-arrays in one dimension and in multiple dimensions.

One-dimensional subarrays

In [16]:
x = np.arange(10)
x
Out[16]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [17]:
x[:5]  # first five elements
Out[17]:
array([0, 1, 2, 3, 4])
In [18]:
x[5:]  # elements after index 5
Out[18]:
array([5, 6, 7, 8, 9])
In [19]:
x[4:7]  # middle sub-array
Out[19]:
array([4, 5, 6])
In [20]:
x[::2]  # every other element
Out[20]:
array([0, 2, 4, 6, 8])
In [21]:
x[1::2]  # every other element, starting at index 1
Out[21]:
array([1, 3, 5, 7, 9])
A potentially confusing case is when the step value is negative. In this case, the defaults for start and stop are swapped. This becomes a convenient way to reverse an array:
In [22]:
x[::-1]  # all elements, reversed
Out[22]:
array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
In [23]:
x[5::-2]  # reversed every other from index 5
Out[23]:
array([5, 3, 1])

Multi-dimensional subarrays

Multi-dimensional slices work in the same way, with multiple slices separated by commas. For example:
In [24]:
x2
Out[24]:
array([[12,  5,  2,  4],
       [ 7,  6,  8,  8],
       [ 1,  6,  7,  7]])
In [25]:
x2[:2, :3]  # two rows, three columns
Out[25]:
array([[12,  5,  2],
       [ 7,  6,  8]])
In [26]:
x2[:3, ::2]  # all rows, every other column
Out[26]:
array([[12,  2],
       [ 7,  8],
       [ 1,  7]])
Finally, subarray dimensions can even be reversed together:
In [27]:
x2[::-1, ::-1]
Out[27]:
array([[ 7,  7,  6,  1],
       [ 8,  8,  6,  7],
       [ 4,  2,  5, 12]])

Accessing array rows and columns

One commonly needed routine is accessing of single rows or columns of an array. This can be done by combining indexing and slicing, using an empty slice marked by a single colon (:):
In [28]:
print(x2[:, 0])  # first column of x2
[12  7  1]
In [29]:
print(x2[0, :])  # first row of x2
[12  5  2  4]
In the case of row access, the empty slice can be omitted for a more compact syntax:
In [30]:
print(x2[0])  # equivalent to x2[0, :]
[12  5  2  4]

Subarrays as no-copy views

One important–and extremely useful–thing to know about array slices is that they return views rather than copies of the array data. This is one area in which NumPy array slicing differs from Python list slicing: in lists, slices will be copies. Consider our two-dimensional array from before:
In [31]:
print(x2)
[[12  5  2  4]
 [ 7  6  8  8]
 [ 1  6  7  7]]
Let's extract a 2×2 subarray from this:
In [32]:
x2_sub = x2[:2, :2]
print(x2_sub)
[[12  5]
 [ 7  6]]
Now if we modify this subarray, we'll see that the original array is changed! Observe:
In [33]:
x2_sub[0, 0] = 99
print(x2_sub)
[[99  5]
 [ 7  6]]
In [34]:
print(x2)
[[99  5  2  4]
 [ 7  6  8  8]
 [ 1  6  7  7]]
This default behavior is actually quite useful: it means that when we work with large datasets, we can access and process pieces of these datasets without the need to copy the underlying data buffer.

Creating copies of arrays

Despite the nice features of array views, it is sometimes useful to instead explicitly copy the data within an array or a subarray. This can be most easily done with the copy() method:
In [35]:
x2_sub_copy = x2[:2, :2].copy()
print(x2_sub_copy)
[[99  5]
 [ 7  6]]
If we now modify this subarray, the original array is not touched:
In [36]:
x2_sub_copy[0, 0] = 42
print(x2_sub_copy)
[[42  5]
 [ 7  6]]
In [37]:
print(x2)
[[99  5  2  4]
 [ 7  6  8  8]
 [ 1  6  7  7]]

Reshaping of Arrays

Another useful type of operation is reshaping of arrays. The most flexible way of doing this is with the reshape method. For example, if you want to put the numbers 1 through 9 in a 3×3 grid, you can do the following:
In [38]:
grid = np.arange(1, 10).reshape((3, 3))
print(grid)
[[1 2 3]
 [4 5 6]
 [7 8 9]]
Note that for this to work, the size of the initial array must match the size of the reshaped array. Where possible, the reshape method will use a no-copy view of the initial array, but with non-contiguous memory buffers this is not always the case.
Another common reshaping pattern is the conversion of a one-dimensional array into a two-dimensional row or column matrix. This can be done with the reshape method, or more easily done by making use of the newaxis keyword within a slice operation:
In [39]:
x = np.array([1, 2, 3])

# row vector via reshape
x.reshape((1, 3))
Out[39]:
array([[1, 2, 3]])
In [40]:
# row vector via newaxis
x[np.newaxis, :]
Out[40]:
array([[1, 2, 3]])
In [41]:
# column vector via reshape
x.reshape((3, 1))
Out[41]:
array([[1],
       [2],
       [3]])
In [42]:
# column vector via newaxis
x[:, np.newaxis]
Out[42]:
array([[1],
       [2],
       [3]])
We will see this type of transformation often throughout the remainder of the book.

Array Concatenation and Splitting

All of the preceding routines worked on single arrays. It's also possible to combine multiple arrays into one, and to conversely split a single array into multiple arrays. We'll take a look at those operations here.

Concatenation of arrays

Concatenation, or joining of two arrays in NumPy, is primarily accomplished using the routines np.concatenate, np.vstack, and np.hstack. np.concatenate takes a tuple or list of arrays as its first argument, as we can see here:
In [43]:
x = np.array([1, 2, 3])
y = np.array([3, 2, 1])
np.concatenate([x, y])
Out[43]:
array([1, 2, 3, 3, 2, 1])
You can also concatenate more than two arrays at once:
In [44]:
z = [99, 99, 99]
print(np.concatenate([x, y, z]))
[ 1  2  3  3  2  1 99 99 99]
It can also be used for two-dimensional arrays:
In [45]:
grid = np.array([[1, 2, 3],
                 [4, 5, 6]])
In [46]:
# concatenate along the first axis
np.concatenate([grid, grid])
Out[46]:
array([[1, 2, 3],
       [4, 5, 6],
       [1, 2, 3],
       [4, 5, 6]])
In [47]:
# concatenate along the second axis (zero-indexed)
np.concatenate([grid, grid], axis=1)
Out[47]:
array([[1, 2, 3, 1, 2, 3],
       [4, 5, 6, 4, 5, 6]])
For working with arrays of mixed dimensions, it can be clearer to use the np.vstack (vertical stack) and np.hstack (horizontal stack) functions:
In [48]:
x = np.array([1, 2, 3])
grid = np.array([[9, 8, 7],
                 [6, 5, 4]])

# vertically stack the arrays
np.vstack([x, grid])
Out[48]:
array([[1, 2, 3],
       [9, 8, 7],
       [6, 5, 4]])
In [49]:
# horizontally stack the arrays
y = np.array([[99],
              [99]])
np.hstack([grid, y])
Out[49]:
array([[ 9,  8,  7, 99],
       [ 6,  5,  4, 99]])
Similary, np.dstack will stack arrays along the third axis.

Splitting of arrays

The opposite of concatenation is splitting, which is implemented by the functions np.split, np.hsplit, and np.vsplit. For each of these, we can pass a list of indices giving the split points:
In [50]:
x = [1, 2, 3, 99, 99, 3, 2, 1]
x1, x2, x3 = np.split(x, [3, 5])
print(x1, x2, x3)
[1 2 3] [99 99] [3 2 1]
Notice that N split-points, leads to N + 1 subarrays. The related functions np.hsplit and np.vsplit are similar:
In [51]:
grid = np.arange(16).reshape((4, 4))
grid
Out[51]:
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
In [52]:
upper, lower = np.vsplit(grid, [2])
print(upper)
print(lower)
[[0 1 2 3]
 [4 5 6 7]]
[[ 8  9 10 11]
 [12 13 14 15]]
In [53]:
left, right = np.hsplit(grid, [2])
print(left)
print(right)
[[ 0  1]
 [ 4  5]
 [ 8  9]
 [12 13]]
[[ 2  3]
 [ 6  7]
 [10 11]
 [14 15]]
Similarly, np.dsplit will split arrays along the third axis.

JOB in 2019

Automated - Digital One o One Meetings- An Idea

                                            Automated - Digital One o One Discussion                                                       ...