xxxxxxxxxx
#generate a list from map iterable with lambda expression
list( map(lambda x: x*2, numeros) )
xxxxxxxxxx
# The map function applies a function to every item in a list,
# and returns a new list.
numbers = [0, -1, 2, 3, -4]
def square_func(n):
return n*n
new_numbers = list(map(square_func, numbers))
#new_numbers: [0, 1, 4, 9, 16]
xxxxxxxxxx
# Let's define general python function
>>> def doubleOrNothing(num):
return num * 2
# now use Map on it.
>>> map(doubleOrNothing, [1,2,3,4,5])
<map object at 0x7ff5b2bc7d00>
# apply built-in list method on Map Object
>>> list(map(doubleOrNothing, [1,2,3,4,5])
[2, 4, 6, 8, 10]
# using lambda function
>>> list(map(lambda x: x*2, [1,2,3,4,5]))
[2, 4, 6, 8, 10]
xxxxxxxxxx
# Python program to demonstrate working
# of map.
# Return double of n
def addition(n):
return n + n
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))
# result [2, 4, 6, 8]
xxxxxxxxxx
#### Core python use case #####
#map(func_name, some_list)
items = [1, 2, 3, 4]
list(map(lambda x: x + 2 , items)) ## [3, 4, 5, 6]
#### Dataframe Application #####
# Method 1
df["col"].apply(lambda x: x+1)
# Method 2
genders = {'James': 'Male', 'Jane': 'Female'}
df['gender'] = df['name'].map(genders)
xxxxxxxxxx
product = 1
list = [1, 2, 3, 4]
for num in list:
product = product * num
# product = 24
xxxxxxxxxx
'''
Map:
A standard function that accepts at least "two-arguments",
a function and an "iterable"
Iterable - something that can be iterated over (list, dictionary,
strings, sets, tuples)
runs the Lambda for each value in the iterable and
returns a map object which can be converted into another data structure
Keyword:
map(function/lambda func., variable)
'''
# Example:
nums = [1,2,3,4]
power = map(math.pow(2), nums)
print(list(power)) # 1, 4, 9, 16
powerLamb = map(lambda x: x**2, nums) # 1, 4, 9, 16
xxxxxxxxxx
# Python program to demonstrate working
# of map.
# Return double of n
def addition(n):
return n + n
# We double all numbers using map()
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))