Python: Print Variables and User Input

Print

The basic Print statement in Python is Print “” – note Print ” also works. You can choose either single or double quotes, but you cannot mix them in the same statement.

Print Variables

Printing variables in Python is a bit more complicated.

If the variable you want to print is a number, use the special string %d inside the quotes and % variable outside the quotes.

If you have more than one variable, you need to have a %d for each variable. Then place your variables inside () at the end of the print line.

pyprint.jpgT

To print a string, you use %s. Notice below you can mix strings and numbers in the same line.

pyprint1.jpg

You can use %r if you are not sure what value the variable will have. It will print both.

User Input

raw_input() allows you ask the user for input.

You can assign the user input to a variable.

You can also pre-define what kind of input you want. Note the error in the second instance. x = int(raw_input()) means I am looking for an integer as input.

pyprint2

If I enter an integer, I do not get the error.

pyprint3.jpg


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT. 

Follow this link for more Python content: Python

Python: Line Graph

Let’s build on what we learned in : Python: Intro to Graphs

First, import pyplot from matplotlib

Remember %matplotlib inline let’s you see your graphs in the jupyter notebooks

pythonLine

Line 1

Note I am using a list comprehension to fill the x axis.

pythonLine1

Now, let us do some formatting:

  • ‘r:’    –   red dotted line
  • label = ‘up’   –  adds label to the line
  • py.legend(loc=9)  – adds a legend to the chart

pythonLine2

Line 2

For line 2, I want to create a reverse curve:

  • d = u  – list u is copied to d
  • d.reverse() – reverses values in d

pythonLine3

Plot the line.

  • ‘g-.’ – green dashed line

pythonLine4

Combine the two lines

pythonLine5

Line 3

Here I use another list comprehension  and zip to make our last like. This adds each element of list u and d in order.

  • ‘b-‘ – blue solid line

pythonLine6


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT. 

Follow this link for more Python content: Python

Python: Pandas Intro (Dataframes)

Before we continue onto Dataframes, I want to clear up something from the Series exercise. Note the line (from pandas import Series, DataFrame)

pandas1

Using that line, I can call upon Series or DataFrame directly in my code

pandas2

In this example below, I did not directly import the methods Series and DataFrame, so I when I tried x = Series() I go an error.

I had to use the full method name of pd.Series() for this to work.

pdDF

DataFrame

DataFrames provide another level of data management for Python. Those of you who come from a more data driven background with appreciate DataFrames.

Let’s start by creating dictionary.

pdDF1.jpg

Now, pass the dictionary to the method DataFrame()

Note, now you have a table looking structure with named columns

pdDF2

You can call up a list of indexes or columns using the methods below:

pdDF3.jpg

DataFrame.info() will return a summary of your DataFrame

pdDF4

Head and Tail

Create a new DataFrame from a dictionary

pdDF5.jpg

If you want just see a few of the first elements, you can use the head() method

pdDF6

The tail() method does the last few. You can even choose how many rows you want.

pdDF7

Describe

The describe() method gives you some quick statistics on any numeric column

pdDF8.jpg

Slice

You can slice a DataFrame just as you would a list

pdDF9

Choose What to Display

DataFrames allow you to filter what rows to display by value or column

pdDF10

There is a lot more you can do with Series and DataFrame in pandas, and we will be covering them in later lessons. For now though, I think you have a general idea.


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT. 

Follow this link for more Python content: Python

 

 

Python: Pandas Intro (Series)

Pandas adds some great data management functionality to Python. Pandas allows you to create series and dataframes.

Series

Think of a series as combination of a list and a dictionary.

To use pandas, first we need to import it.

pandas1

To create as series with pandas, use the following syntax

  • variable = Series([item1, item2, … item_n])

** note Series is capitalized. This method is case sensitive

pandas Series can contain numbers or strings. You call elements in a Series like you do a list. variable[index]

pandas2

You can create you own index in a Series as well, making it function a lot like a dictionary.

Notice with the syntax leg[leg==4] I am able to filter by items equal to 4

pandas3

If you have an existing dictionary, you can convert it into a pandas Series

pandas4

You can call the index and values of a Series using the following methods:

pandas5


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT. 

Follow this link for more Python content: Python

 

 

 

Python: Numpy

First off, CONGRATS for making it this far. Numpy really signifies the first step in real data science with Python.

Numpy is a library that adds advanced mathematical capabilities to Python. If you are using the Anaconda release of iPython, you already have numpy installed. If not, you will need to go over to their site and download it. Link to numpy site: www.numpy.org

Numpy adds multi-dimensional array capabilities to Python. It also provides mathematical tools for dealing with these arrays.

Array

What is an array? In different programming languages, arrays are equivalent to lists in Python. In fact, a single dimension array in Python can be used interchangeably with lists in most cases.

What makes arrays special in Python is the ability to make multidimensional arrays. Those who have taken math courses like Linear Algebra will better know multidimensional arrays by the term matrix. And if you paid attention in Linear Algebra, you will know there is a lot of cool things you can do with matrices.

For those who didn’t take Linear Algebra (you probably went out and made friends and had a social life), don’t worry, I will fill you in on what you need to know.

Numpy

Let’s start by creating a single dimension array

  • import numpy as np   — imports numpy into your notebook, we set the alias to np
  • x = np.array([8,7,4])  — array is a method of np, so the syntax is np.array. **note the [] inside the ()
  • x[1] = you call array just like lists
  • x.shape = shows you shape of your array, since we are single dimension, the answer is a single number – **note 3L – the L indicates integer in Python

pythonnumpy.jpg

Now let’s make a 2 x 3 matrix. When describing a matrix (or multi-dim array) the first number indicates the number of elements across and the second number indicates down. This is standard mathematical notation.

You can see I create a new row by enclosing the number sets in [] separated by a ‘,’

Now when want to call an item from the multi-dim array, you need to use 2 index numbers. y[0,1] = y[row, column]

pythonnumpy2

np.arange()

np.arange() is a command we can use to auto populate an array.

  1. np.arang(5) –create a one – dim array with 5 elements
  2. np.arange(10).reshape(2,5) – reshape lets you convert a one-dim array into a multi-dim array

pythonnumpy4

Transpose

Transposing a matrix means flipping it on its axis. This comes in handy in applications like multi-variate regressions. To transpose our array in Python, we use the “.T” method

pythonnumpy5.jpg

dot Product

Performing a dot product on a matrix is a useful calculation, but it is very time consuming. Numpy makes it easy though.

pythonnumpy6.jpg

If you need a brush up on dot products, this is a great link: matrix multiplication


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT. 

Follow this link for more Python content: Python

 

 

Python: **Kwargs and *Args

Outside of beings incredibly fun to say, Kwargs and Args can be pretty useful.

Here is how they work. Let us say you wanted to make a function that adds 4 numbers:

Notice what happens when we only provide 3 arguments, we error out. The same thing happens if we try to give the function 5 arguments.

pythonkwa

Well, if the world perfectly predictable, this wouldn’t be an issue. But in the real world, making a function that adds 4 and only 4 numbers isn’t very useful. A function that can add any given set of numbers however is very useful.

*args

*args to the rescue

Using the keyword *args inside the function parenthesis gives you the flexibility of having as many, or as few arguments as you want.

pythonkwa1.jpg

**kwargs

Kwargs are basically args with keywords. Think dictionaries.

pythonkwa2

You can combine regular arguments with *args and **kwargs

pythonkwa3

You can call functions with *args and **kwargs

oh, in case I forgot to mention earlier arg and kwarg are not required as keywords. As you can see in the examples below, it is the * or ** you need.

pythonkwa4.jpg


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT. 

Follow this link for more Python content: Python

 

Python: Regular Expressions

Regular Expressions are used to parse text. In the world of Big Data, being able to work with unstructured text is a big advantage.

To use regular expressions, first you must import the module. This is done by placing the command import re at the top of your code.

re.search()

Now, let us examine this code below:

We want to see if dog (assigned to x) is in the sentence ‘I just a saw dog. He was chasing a cat.'(assigned to y)

Using the search() method from re, we ask if re.search(x,y). Note you place the item you are searching by first in the parenthesis. re.search() returns a boolean value (True, False).

pythonreg

You can use re.search with lists of search items as well.

Here z is taking one item from the list x at a time and running it through re.search. Notice ‘one’ returns True, while ‘two’ returns false.

pythonreg1.jpg

re.findall()

re.findall returns all instances of your search term. Notice it found water whether it was a stand alone word, or part of a larger word.

pythonreg2.jpg

re.split()

The re.split() method does pretty much what you would think it does. You can pick a delimiter and the method will split your string at that delimiter.

In the example below, ‘;‘ is my delimiter. Notice how it split my string in two, plus removed the delimiter for me.

pythonreg3

use re.search() to find position

You can use re.search() to find the starting and ending position of a search item in a string

pythonreg4

exclusion

If you want to exclude characters, use the ^ between square brackets [].

This example excludes the letter s = [^s] and puts the remaining characters in a list

In the second example, I add + after the []. This keeps all the characters together.

pythonreg5.jpg

This next example is a useful tool you will find yourself using in text mining. Here we use [^?!. ]+ to remove punctuation.

pythonreg6


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT. 

Follow this link for more Python content: Python

 

 

Python: Enumerate() and Sort

Enumerate

Enumerate is a useful function in Python as it returns both the indexes and values of Lists.

Let’s look at the code:

Running the list through a For loop, we assign the index to x and the value to y

pythonEnum

Let’s say we only wanted to print every other value in a list

To do that, I could run a simple nested an IF statement inside my loop stating if the index an even number, then print the value. (x%2==0 is an easy trick for finding even or odd values. % means modulus – it returns the remainder of a division problem. Any even number divided by 2 will not have a remainder – so the modulus will be 0)

pythonEnum1

Sort

Python lists come with a two built in sort functions.

sorted()

The first: sorted() – sorts the items in a list, but does not alter the list.

As you can see, sorted(lst) returns a sorted list, but calling lst again shows the list is still in its original order.

pythonEnum2

To sort the items in descending order use the reverse=True command:

pythonEnum3

list.sort()

list.sort() is a method – meaning it is a function found with the class List.

list.sort() sorts items in a list and alters position of the items in the actual list. So the next time you run the list, the items are sorted in the list.

Also note that reverse = True works in the list.sort() method as well.

pythonEnum4


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT. 

Follow this link for more Python content: Python

 

Python: Generators

I apologize in advanced as this topic is going to get a little computer sciency. Unfortunately there is no way around it. At first look, generators are going to resemble all the other iterables we have covered so far. But unlike loops we have used so far, generators produce iterables “lazily”.

So what do I mean by “lazily”?

Let’s consider this infinite loop I created below. This will run forever, producing a List (at least until your computer’s memory runs out). And that is the issue. Eventually the computer will run out of memory.

pythonGen

**note if you actually decide to run the code above, you will need to force it to stop. Just closing the notebook won’t do it. Go to File>Close and Halt to stop this loop from running and eventually crashing your PC.

pythonGen1

This becomes are consideration when working with large data sets. The more memory you chew up, the worse you performance. So a work around is to use generators. Generators produce the data lazily, meaning they produce the iterator, yield it, and then forget it – they don’t put the values into a List like regular iterators do. They only yield one iterator at a time.

Notice my continued use of the world yield? There is a reason for that. Look at the code for a generator below:

Note that generators have to be functions. The yield command – which signifies a generator,  cannot be used outside of a function.

pythonGen2.jpg

Now, I know this looks like I am actually repeating work here. I mean I am using two loops to do what I could do with one loop. This issue arises when we have large numbers. If you are only iterating a few hundred numbers, you probably don’t need to worry about generators. However, if you are going to be iterating 100,000 elements, you will see some major performance improvements by using the code above.

Range() and Xrange()

Python has a built in generator function: xrange(). This will produce a range of numbers – just like range() does – but the xrange() function works “lazily” (i.e. doesn’t chew up memory)

In Python 3 – range() is now a generator as well.


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT. 

Follow this link for more Python content: Python