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?
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 .
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.
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 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.
The syntax is map(function, list)
.
Example:
map(len, [ [ 1,2,3], [4,5,6] ])
Output:
[ 3, 3 ]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With