Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python vs. R: apply a function to each element in a vector

Tags:

I want to apply a function (len) over each element in a vector. In R I can easily do this with sapply(cities,char). Is there an alternative like this in Python WITHOUT writing a loop?

like image 998
Sylvi0202 Avatar asked Dec 15 '16 18:12

Sylvi0202


People also ask

Which command applies the function to each element in the given vector and returns a list that contains all the results?

Description. lapply returns a list of the same length as X , each element of which is the result of applying FUN to the corresponding element of X .

What does apply () do in R?

The apply() function lets us apply a function to the rows or columns of a matrix or data frame. This function takes matrix or data frame as an argument along with function and whether it has to be applied by row or column and returns the result in the form of a vector or array or list of values obtained.

How do I apply a function to a dataset in R?

In R Programming Language to apply a function to every integer type value in a data frame, we can use lapply function from dplyr package. And if the datatype of values is string then we can use paste() with lapply.

How do I apply a function to an array in R?

How to Use apply() function to Array in R. To use the apply() function in an array, create an array using vectors, and then use the apply() function to perform the specific operations. Let's define two vectors to form an array. Now, to create an array, use the array() function and pass these two vectors.


2 Answers

The syntax is map(function, list).

Example:

map(len, [ [ 1,2,3], [4,5,6] ])

Output:

[ 3, 3 ]
like image 94
Elliott Beach Avatar answered Oct 08 '22 21:10

Elliott Beach


The R sapply() could be replaced with a list comprehension, but fair enough a list comprehension doesn't strictly avoid the writing of a loop.

In addition to map() you should take a look at Pandas, which provides Python alternatives to several of the functionality that people use in R.

import pandas as pd

vector = [1,2,3,4,5]
square_vector = pd.Series(vector).apply(lambda x: x**2)  
print square_vector.tolist()

The above code results in a new list with the square values of the imput:

[1, 4, 9, 16, 25]

Here, I passed the vector to a series constructor pd.Series(vector) and apply an anonymus function apply(lambda x: x**2). The output is a pandas series which can be converted back to a list if desired tolist(). Pandas series have a lot of functionalities and are ideal for many data manipulation and analysis tasks.

like image 43
Katherine Mejia-Guerra Avatar answered Oct 08 '22 20:10

Katherine Mejia-Guerra