Raw Python - Maps

Mapping is basically mapping one value to another one, almost like a dictionary. This is a functional programming concept but can be useful in certain circumstances and will certainly come up in your data analysis career. This is a fundamental part of the MapReduce style of programming popular in big data.


In [1]:
from __future__ import print_function

In [2]:
x = range(0,10)

In [3]:
x


Out[3]:
range(0, 10)

we’ll have a list of things and we’ll want to repeat a transformation over and over again to each item in the list.


In [4]:
def cube(num):
    return num ** 3

For example you may want to cube every item


In [5]:
for item in x:
    print(cube(item))


0
1
8
27
64
125
216
343
512
729

In [6]:
new_list = []
for item in x:
    new_list.append(cube(item))

In [7]:
print(new_list)


[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

In [8]:
map_list = map(cube, x)
print(list(map_list))


[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

Exercises:

  • Create a map that transforms a list of integers into their square roots

  • Create a map that transforms a list of floats into integers


In [9]:
fx = map(float, range(10))
print(list(fx))


[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]

In [10]:
fx = map(float, range(10)) # have to create it again in python 3

In [11]:
print(list(map(int, fx)))


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [12]:
from math import sqrt

In [13]:
print(list(map(sqrt, x)))


[0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979, 2.449489742783178, 2.6457513110645907, 2.8284271247461903, 3.0]