Programming with Python

February 22, 2020
4 mins read

Motivation

In order to do proper hands-on with a new language, it’s important to understand each part of it by applying live examples. Hence its syntax fully clear.


Let’s start by playing with functions;

Functions

  • Simply create an add_numbers a function that takes two numbers and adds them together;
  • add_numbers updated to take an optional 3rd parameter.
  • add_numbers updated to take an optional flag parameter.
  • Assign function add_numbers to variable add.

Types and Sequences

  • Tuples are an immutable data structure (cannot be altered).
  • Lists are a mutable data structure.
  • Use append to append an object to a list.
  • And by using the indexing operator.
  • Use to concatenate lists
  • Use * to repeat lists
  • Use the in operator to check if something is inside a list.
  • Let’s look at the strings. Use bracket notation to slice a string.
  • To return the last element of the string.
  • This will return the slice starting from the 4th element from the end and stopping before the 2nd element from the end.
  • This is a slice from the beginning of the string and stopping before the 3rd element.
  • And this is a slice starting from the 4th element of the string and going all the way to the end.
  • Split returns a list of all the words in a string, or a list split on a specific character.
  • * Make sure we convert objects to strings before concatenating.
  • Dictionaries associate keys with values.
  • Iterate over all of the keys
  • Iterate over all of the values
  • We can unpack a sequence into different variables:
  • Make sure the number of values you are unpacking matches the number of variables being assigned.

More on Strings

  • Again, we have to use string type here;
  • Python has a built-in method for convenient string formatting.

Dates and Times

For Dates and Times, we’ve to import “datetime” and “time” libraries;

  • time” returns the current time in seconds since the Epoch. (January 1st, 1970)
  • Convert the timestamp to datetime.
  • Handy datetime attributes.
  • timedelta is a duration expressing the difference between two dates.
  • date.today returns the current local date.

Objects and map()

  • An example of a class in python
  • An example of mapping the min function between two lists.
  • Now let’s iterate through the map object to see the values.

Lambda and List Comprehensions

Lambda’s are Python’s way of creating anonymous functions. These are the same as other functions, but they have no name. The intent is that they’re simple or short-lived and it’s easier just to write out the function in one line instead of going to the trouble of creating a named function. The return of a lambda is a function reference.

Note that we can’t have default values for lambda parameters and we can’t have complex logic inside of the lambda itself because we’re limited to a single expression.

So lambdas are really much more limited than full function definitions. But they’re very useful for simple little data cleaning tasks. And we can see lots of examples regarding that. So we should be able to read and write lambdas.

Here’s an example of lambda that takes in three parameters and adds the first two.

  • Let’s iterate from 0 to 999 and return the even numbers.

Numerical Python (NumPy)

  • Let’s start with importing; “import numpy as np

Creating Arrays

  • Create a list and convert it to a numpy array
  • We can also just pass in a list directly
  • Pass in a list of lists to create a multidimensional array.
  • Use the shape method to find the dimensions of the array. (rows, columns)
  • Arrange returns evenly spaced values within a given interval.
  • Reshape returns an array with the same data with a new shape.
  • Linspace returns evenly spaced numbers over a specified interval.
  • Resize changes the shape and size of the array in-place.
  • Ones return a new array of given shape and type, filled with ones.
  • zeros return a new array of given shape and type, filled with zeros.
  • Eye returns a 2-D array with ones on the diagonal and zeros elsewhere.
  • Diag extracts a diagonal or constructs a diagonal array.
  • Create an array using repeating list (or see np.tile)
  • Repeat elements of an array using repeat.

Combining Arrays

  • Use vstack to stack arrays in sequence vertically (row wise).
  • Use hstack to stack arrays in sequence horizontally (column wise).

Operations

  • Use +, -, *, / and ** to perform element-wise addition, subtraction, multiplication, division and power.
  • elementwise power
  • Dot Product
  • number of rows of the array
  • Let’s look at transposing arrays. Transposing permutes the dimensions of the array.
  • The shape of the array z is (2,3) before transposing.
  • Use .T to get the transpose.
  • The number of rows has swapped with the number of columns.
  • Use .dtype to see the data type of the elements in the array.
  • Use .astype to cast to a specific type.

Math Functions

  • Numpy has many built-in math functions that can be performed on arrays.

Indexing / Slicing

  • Use bracket notation to get the value at a specific index. Remember that indexing starts at 0.
  • Use “:” to indicate a range. array[start:stop]. (Leaving start or stop empty will default to the beginning/end of the array.)
  • Use negatives to count from the back.
  • A second “:” can be used to indicate step-size. array[start:stop:stepsize]. (Here we are starting 5th element from the end, and counting backwards by 2 until the beginning of the array is reached.)
  • Let’s look at a multidimensional array.
  • Use bracket notation to slice: array[row, column]
  • And use “:” to select a range of rows or columns
  • Here we are selecting all the rows up to (and not including) row 2, and all the columns up to (and not including) the last column.
  • This is a slice of the last row and only every other element.
  • We can also perform conditional indexing. Here we are selecting values from the array that are greater than 30. (Also see np.where)
  • Here we are assigning all values in the array that are greater than 30 to the value of 30.

Copying Data

* Be careful with copying and modifying arrays in NumPy!

  • r2 is a slice of r
  • Set this slice’s values to zero ([:] selects the entire array)
  • r has also been changed!
  • To avoid this, use r.copy to create a copy that will not affect the original array
  • Now when r_copy is modified, r will not be changed.

Iterating Over Arrays

  • Let’s create a new 4 by 3 array of random numbers 0-9.
  • Iterate by row
  • Iterate by index:
  • Iterate by row and index:
  • Use zip to iterate over multiple iterables.

Conclusion

Further, one can perform further hands-on of different techniques like Reading and Writing data to/from csv/spreadsheets and also by using different python libraries. : – )

Data Scientist & Solution Architect || IBM Recognised Speaker, Mentor, and Teacher || Debater || Blogger || Guinness World Record Holder || Watson Solution Developer || IBM Community Activist || Aspiring to Inspire.

Leave a Reply

Your email address will not be published.

Previous Story

Who is a Man!

Next Story

Hands-On with Supervised & Unsupervised Learning | Machine Learning

Latest from Blog

Quantum Computing | What, Why & How

Now as we are starting the 5th decade after the very first proposed model in the 1980s, quantum computers are now commercially available, brought out of the lab, and into the industry by IBM Quantum. With many experts predicting it will revolutionize the way we approach problem-solving. With the recent

Case Study: Digital Transformation of “justSajid Bank”

In this current era of what we call “digital first”, industries are repeatedly changing and evolving with the help of technology. So as the banking industry is reshaping itself, banks need to keep adopting positive changes to counter and overcome the key challenges of the modern world to overcome the

Metaverse || A Whole New World.

Things are going to be super dramatic in the next few years. Metaverse is going to open a lot of new doors to revise things that we are doing now. The culture and lifestyle would be changed. Some new cultures would have emerged and everybody would be living without physical

Pakistan Day 2020 | Coronavirus Technical Solutions

Well, on Pakistan Day 2020 our nation along with the rest of the world is facing Corona Pandemic. As the sons of this great motherland, we are trying to play our roles at our places. Within the last few weeks, Alhamdulillah I’ve got a chance to develop two technical solutions

Password: Choose the Secure, Easy and Cool Password

A super secure Password is very common nowadays. Although according to experts the password is going to expire very soon. Moreover, the pin codes are also replacing password in some why. Perhaps still there is a lot of importance of a secure password in many places. The one of the most

JumpStart with DevOps

What is DevOps; DevOps is a Software Development Strategy, that bridges the gap between the Dev and the Ops side of the company. * It’s not a tool, it’s a Methodology to bridge the gap b/w development and operations teams! As there is always a lot of conflicts between the

JumpStart Programming with Python 3

Motivation; Well, if you want to play with data and deal with complex analytics problems then Python is the best for you. We can use Python for developing complex scientific and numeric apps. Python is designed with features to facilitate data analysis and visualization. The syntax in Python helps the programmers to do coding

Understanding of Data Science Methodology

Motivation: It’s all about the different methods used in data science. Data Science Methodology: There is the following methodology used in data science which can further categories into different phases; From Problem to Approach Business Understanding Analytical Approach Working with Data Data Requirements Data Collection Data Understanding Data Preparation Deriving the

Understanding Machine Learning Methodology

Motivation Well, if we talk about a human cell sample extracted from a patient. The cell would have some characteristics. One of the interesting questions we can ask, what kind of statistics that cell have? One could easily presume that only a doctor with years of experience could diagnose a tumor and

SIMPLE NAVIGATION IN WINDOWS APPLICATION

The Navigation of UWP Apps is extremely cool and easier than other platforms. It allows enabling a variety of intuitive user experiences for moving between apps, pages, and content. Navigation is the key part of the Application. In your small Apps, you may maintain your contents and functionality in a

UNDERSTANDING THE ARCHITECTURE OF UNIVERSAL WINDOWS PLATFORM

The architecture of Universal Windows Platform is most exclusive with the center of gravity which is One Windows Core. Now the whole development will follow the common refactored core that will common for all the windows Releases. It’s all about One Core, One Hardware Platform, Universal Hardware Driver and Standalone

Guinness World Record Holder | Hajj Hackathon | Khadim Al-Haramain Al-Sharifain

Khadim Al-Haramain Al-Sharifain Built an MVP of a cognitive platform name “Khadim Al-Haramain Al-Sharifain“.  Objective The objective was to facilitate Hajj operations by introducing cognitive services integrated with Hajj systems. Hence millions of Muslims who are there for Allah Rab-ul-Izat, can perform anything without disturbing their focuses and concentrations.  Functionalities

JumpStart with IBM Bluemix

IBM Bluemix is the world most exclusive cloud platform that provides developers to quickly develop, Deploy and manage Apps over the cloud without dealing with any underline infrastructure. Bluemix provides great open source platforms for your needs. Tech experts believe that up to 2020 the computing era would completely change.

JumpStart Into Big Data With HDInsight

What would happen when the volume of your data increased repeatedly over time and you need high velocity at the same time. Not only that but you have a different variety of data and Variability also exists in your data. So how would you handle all that data? If we

Microsoft SharePoint: Create an Intranet in SharePoint

As you should already have some hands on with SharePoint. So, Lets do some hands on with SharePoint Intranet for Small company. Simply start with a Blank Site Collection. Let’s assume that the company has 3 Departments: Sales, Production and Support. They each have their own area in which they should

.NET Core

.NET Core 1.0  .NET Core 1.0 is a major new investment in the future of .NET and laying the foundation for decades to come. Still, it is in its early stage, and for some time you might still focus .NET Framework 4.6 depending on your application needs. But for many scenarios,

JUMPSTART WITH DATA BINDING IN UWP

Data Binding is one of the most interesting topics in Universal App Development. In order to perform the better functionality, you really need to have some great usage of Data Binding in you Apps. So! First thing first. What is actually the Data Binding and is its usage in UWP.

justSajid | A PLACE FOR MY THOUGHTS

This blog is my personal mental playground. The views expressed are mine, and mine alone. They do not represent the views of my employer, my family, my friends, my imaginary friends, my neighbors, people who live in my city, province, country, region, or planet, nor do they represent the views

justSajid | A PLACE FOR MY THOUGHTS

justSajid is my personal mental playground. The views expressed are mine, and mine alone. They do not represent the views of my employer, my family, my friends, my imaginary friends, my neighbors, people who live in my city, province, country, region, or planet, nor do they represent the views of

Agentic AI: The Future of Machines Acting with Purpose

Artificial Intelligence (AI) has come a long way from being a fancy algorithm for chess games to becoming our digital assistant, creative collaborator, and even a philosopher’s muse. One of the more intriguing advancements in AI is Agentic AI—an AI system that can act autonomously, pursue goals, and make decisions,
GoUp