Home > Enterprise >  Applying map function over row
Applying map function over row

Time:10-28

I want to apply map function over rows in 2d array.

Like this:

[['1', 'apple'], ['2', 'banana']]

to

[[1, 'apple'], [2, 'banana']]

numpy.apply_along_axis works, but want to know using map() function.

CodePudding user response:

You can do:

lst = [['1', 'apple'], ['2', 'banana']]

[*map(lambda x: [int(x[0]), x[1]], lst)]
# [[1, 'apple'], [2, 'banana']]

But I never consider this particularly nice or readable. Compare this with the comprehension

[[int(a), b] for a, b in lst]
# [[1, 'apple'], [2, 'banana']]

CodePudding user response:

You still map over the entire row, but the function you map will return a new row containing part of the original untouched.

>>> list(map(lambda row: [int(row[0]), row[1]], [['1', 'apple'], ['2', 'banana']]))
[[1, 'apple'], [2, 'banana']]

Since the nested list isn't a single data structure (it's a list of lists), there's no way to only map over a column, because there is no explicit column object to operate on.

CodePudding user response:

map, as you might know, iterates over a iterable and runs a given function with the current element as its argument, and returns the result of that function.

so to use map with a 2D array, first create a function that takes in each element of the parent 1D array as an argument.

considering your example with array as [['1', 'apple'], ['2', 'banana']]

def map_function(item):
    return [int(item[0], item[1])]

now map will pass each element of the 1D array i,e. ['1', 'apple'] , ['2', 'banana'] , one by one to map_function which in turn will convert the 0th element in the passed list to an int.

now just pass this function to map along with the 2D array.

2D_array = [['1', 'apple'], ['2', 'banana']]
resultant_2D = list(map(map_function, 2D_array))
# [[1, 'apple'], [2, 'banana']]

the solution by @chepner uses lambda or anonymous function instead of defining a function to make the code concise, but it all works the same :)

  • Related