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]:
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))
In [6]:
new_list = []
for item in x:
new_list.append(cube(item))
In [7]:
print(new_list)
In [8]:
map_list = map(cube, x)
print(list(map_list))
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))
In [10]:
fx = map(float, range(10)) # have to create it again in python 3
In [11]:
print(list(map(int, fx)))
In [12]:
from math import sqrt
In [13]:
print(list(map(sqrt, x)))