Questions tagged [apply]

A function to call another function with a list of arguments.

apply
Filter by
Sorted by
Tagged with
1155 votes
12 answers
440k views

Grouping functions (tapply, by, aggregate) and the *apply family

Whenever I want to do something "map"py in R, I usually try to use a function in the apply family. However, I've never quite understood the differences between them -- how {sapply, lapply, etc.} ...
grautur's user avatar
  • 30.3k
625 votes
8 answers
1.3m views

Create new column based on values from other columns / apply a function of multiple columns, row-wise in Pandas

I want to apply my custom function (it uses an if-else ladder) to these six columns (ERI_Hispanic, ERI_AmerInd_AKNatv, ERI_Asian, ERI_Black_Afr.Amer, ERI_HI_PacIsl, ERI_White) in each row of my ...
Dave's user avatar
  • 7,190
568 votes
8 answers
901k views

How can I use the apply() function for a single column?

I have a pandas dataframe with multiple columns. I want to change the values of the only the first column without affecting the other columns. How can I do that using apply() in pandas?
Amani's user avatar
  • 17.2k
250 votes
6 answers
434k views

Why isn't my Pandas 'apply' function referencing multiple columns working? [closed]

I have some problems with the Pandas apply function, when using multiple columns with the following dataframe df = DataFrame ({'a' : np.random.randn(6), 'b' : ['foo', 'bar'] * 3, ...
Andy's user avatar
  • 9,741
248 votes
7 answers
400k views

python pandas: apply a function with arguments to a series

I want to apply a function with arguments to a series in python pandas: x = my_series.apply(my_function, more_arguments_1) y = my_series.apply(my_function, more_arguments_2) ... The documentation ...
Abe's user avatar
  • 23.3k
236 votes
13 answers
235k views

Return multiple columns from pandas apply()

I have a pandas DataFrame, df_test. It contains a column 'size' which represents size in bytes. I've calculated KB, MB, and GB using the following code: df_test = pd.DataFrame([ {'dir': '/Users/...
PaulMest's user avatar
  • 14.1k
233 votes
5 answers
61k views

When should I (not) want to use pandas apply() in my code?

I have seen many answers posted to questions on Stack Overflow involving the use of the Pandas method apply. I have also seen users commenting under them saying that "apply is slow, and should be ...
cs95's user avatar
  • 392k
210 votes
14 answers
186k views

Remove columns from dataframe where ALL values are NA

I have a data frame where some of the columns contain NA values. How can I remove columns where all rows contain NA values?
Gnark's user avatar
  • 4,180
168 votes
5 answers
24k views

Is R's apply family more than syntactic sugar?

...regarding execution time and / or memory. If this is not true, prove it with a code snippet. Note that speedup by vectorization does not count. The speedup must come from apply (tapply, sapply, ......
steffen's user avatar
  • 2,172
163 votes
7 answers
320k views

Apply a function to every row of a matrix or a data frame

Suppose I have a n by 2 matrix and a function that takes a 2-vector as one of its arguments. I would like to apply the function to each row of the matrix and get a n-vector. How to do this in R? For ...
Tim's user avatar
  • 97.1k
156 votes
4 answers
159k views

Apply function to each cell in DataFrame

I have a dataframe that may look like this: A B C foo bar foo bar bar foo foo bar I want to look through every element of each row (or every element of each column) and ...
eljusticiero67's user avatar
150 votes
4 answers
12k views

Is the "*apply" family really not vectorized?

So we are used to say to every R new user that "apply isn't vectorized, check out the Patrick Burns R Inferno Circle 4" which says (I quote): A common reflex is to use a function in the apply ...
David Arenburg's user avatar
101 votes
6 answers
289k views

R Apply() function on specific dataframe columns

I want to use the apply function on a dataframe, but only apply the function to the last 5 columns. B<- by(wifi,(wifi$Room),FUN=function(y){apply(y, 2, A)}) This applies A to all the columns of y ...
skmathur's user avatar
  • 1,617
100 votes
7 answers
147k views

pandas apply function that returns multiple values to rows in pandas dataframe

I have a dataframe with a timeindex and 3 columns containing the coordinates of a 3D vector: x y z ts 2014-05-15 10:38 0.120117 0.987305 ...
Fra's user avatar
  • 5,088
98 votes
5 answers
102k views

How does the Math.max.apply() work?

How does the Math.max.apply() work?. <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>JS Bin</title> </head> <body> <script> ...
Shane's user avatar
  • 5,587
93 votes
4 answers
44k views

Why are loops slow in R?

I know that loops are slow in R and that I should try to do things in a vectorised manner instead. But, why? Why are loops slow and apply is fast? apply calls several sub-functions -- that doesn't ...
isomorphismes's user avatar
92 votes
2 answers
93k views

What's the .apply jQuery function?

I see that in different plugins and codes, but I don't understand what does that function... In the jQuery api isn't referenced!
CRISHK Corporation's user avatar
91 votes
7 answers
55k views

How can I call a javascript constructor using call or apply? [duplicate]

How could I generalise the function below to take N arguments? (Using call or apply?) Is there a programmatic way to apply arguments to 'new'? I don't want the constructor to be treated like a plain ...
fadedbee's user avatar
  • 43.8k
90 votes
2 answers
86k views

Trouble passing in lambda to apply for pandas DataFrame

I'm trying to apply a function to all rows of a pandas DataFrame (actually just one column in that DataFrame) I'm sure this is a syntax error but I'm know sure what I'm doing wrong df['col'].apply(...
sedavidw's user avatar
  • 11.4k
88 votes
3 answers
27k views

Why is `vapply` safer than `sapply`?

The documentation says vapply is similar to sapply, but has a pre-specified type of return value, so it can be safer [...] to use. Could you please elaborate as to why it is generally safer, maybe ...
flodel's user avatar
  • 88.4k
83 votes
5 answers
164k views

Pandas apply but only for rows where a condition is met

I would like to use Pandas df.apply but only for certain rows As an example, I want to do something like this, but my actual issue is a little more complicated: import pandas as pd import math z = ...
mgoldwasser's user avatar
81 votes
7 answers
58k views

How does require() in node.js work?

I tried this: // mod.js var a = 1; this.b = 2; exports.c = 3; // test.js var mod = require('./mod.js'); console.log(mod.a); // undefined console.log(mod.b); // 2 console.log(mod.c); // 3, ...
Trantor Liu's user avatar
  • 8,980
71 votes
3 answers
121k views

Pandas - combine column values into a list in a new column

I have a Python Pandas dataframe df: d = [['hello', 1, 'GOOD', 'long.kw'], [1.2, 'chipotle', np.nan, 'bingo'], ['various', np.nan, 3000, 123.456]] t = pd.DataFrame(data=d, columns=['A','B','...
clg4's user avatar
  • 2,903
71 votes
2 answers
109k views

Apply function on each row (row-wise) of a NumPy array

So, I have the function - def function(x): x , y = vector return exp(((-x**2/200))-0.5*(y+0.05*(x**2) - 100*0.05)**2) and let's say that I would like to evaluate it at the following points (...
tattybojangler's user avatar
69 votes
3 answers
95k views

How to paste a string on each element of a vector of strings using apply in R?

I have a vector of strings. d <- c("Mon","Tues","Wednes","Thurs","Fri","Satur","Sun") for which I want to paste the string "day" on each element of the vector in a way similar to this. week <-...
pedrosaurio's user avatar
  • 4,798
63 votes
8 answers
196k views

Apply function to each column in a data frame observing each columns existing data type

I'm trying to get the min/max for each column in a large data frame, as part of getting to know my data. My first try was: apply(t,2,max,na.rm=1) It treats everything as a character vector, because ...
Darren Cook's user avatar
  • 28.3k
60 votes
6 answers
31k views

Row-wise iteration like apply with purrr

How do I achieve row-wise iteration using purrr::map? Here's how I'd do it with a standard row-wise apply. df <- data.frame(a = 1:10, b = 11:20, c = 21:30) lst_result <- apply(df, 1, ...
matsuo_basho's user avatar
  • 2,810
57 votes
3 answers
75k views

Use Pandas groupby() + apply() with arguments

I would like to use df.groupby() in combination with apply() to apply a function to each row per group. I normally use the following code, which usually works (note, that this is without groupby()): ...
beta's user avatar
  • 5,546
55 votes
4 answers
18k views

Faster way to read fixed-width files

I work with a lot of fixed width files (i.e., no separating character) that I need to read into R. So, there is usually a definition of the column width to parse the string into variables. I can use ...
Mark Danese's user avatar
  • 2,411
52 votes
4 answers
70k views

Why doesn't Array.push.apply work?

As described here, a quick way to append array b to array a in javascript is a.push.apply(a, b). You'll note that the object a is used twice. Really we just want the push function, and b.push.apply(...
starwed's user avatar
  • 2,563
50 votes
7 answers
173k views

Python pandas apply function if a column value is not NULL

I have a dataframe (in Python 2.7, pandas 0.15.0): df= A B C 0 NaN 11 NaN 1 two NaN ['foo', 'bar'] 2 three 33 NaN I want to apply a ...
ragesz's user avatar
  • 9,329
49 votes
5 answers
66k views

How to apply function over each matrix element's indices

I am wondering if there is a built-in function in R which applies a function to each element of the matrix (of course, the function should be computed based on matrix indices). The equivalent would be ...
eold's user avatar
  • 6,012
48 votes
5 answers
11k views

In Javascript is there equivalent to .apply that doesn't change the value of this?

Seems easy enough, i want to call a function with array of arguments. Sure, i can say func.apply(this, ['some', 'arguments']); but that will change the value of this inside func. Any idea how to do ...
JussiR's user avatar
  • 2,065
47 votes
3 answers
126k views

subset a column in data frame based on another data frame/list

I have the following table1 which is a data frame composed of 6 columns and 8083 rows. Below I am displaying the head of this table1: |gene ID | prom_65| prom_66| amast_69| amast_70| ...
BCArg's user avatar
  • 2,144
42 votes
4 answers
30k views

Scala case class private constructor but public apply method

If I have the following case class with a private constructor and I can not access the apply-method in the companion object. case class Meter private (m: Int) val m = Meter(10) // constructor Meter ...
Erik's user avatar
  • 2,948
41 votes
6 answers
82k views

How do I wrap a function in Javascript?

I'm writing a global error handling "module" for one of my applications. One of the features I want to have is to be able to easily wrap a function with a try{} catch{} block, so that all calls to ...
Daniel Magliola's user avatar
40 votes
2 answers
18k views

Including the group name in the apply function

Is there away to specify to the groupby() call to use the group name in the apply() lambda function? Similar to if I iterate through groups I can get the group key via the following tuple ...
user1129988's user avatar
  • 1,526
39 votes
3 answers
74k views

Concatenate row-wise across specific columns of dataframe

I have a data frame with columns that, when concatenated (row-wise) as a string, would allow me to partition the data frame into a desired form. > str(data) 'data.frame': 680420 obs. of 10 ...
Jubbles's user avatar
  • 4,530
39 votes
3 answers
10k views

Why does pandas apply calculate twice

I'm using the apply method on a panda's DataFrame object. When my DataFrame has a single column, it appears that the applied function is being called twice. The questions are why? And, can I stop ...
piRSquared's user avatar
  • 291k
38 votes
7 answers
38k views

Difference between using a spread syntax (...) and push.apply, when dealing with arrays

I have two arrays, const pets = ["dog", "cat", "hamster"] const wishlist = ["bird", "snake"] I want to append wishlist to pets, which can be done using two methods, Method 1: pets.push.apply(...
Net Myth's user avatar
  • 441
37 votes
4 answers
50k views

use multiple columns as variables with sapply

I have a dataframe and I would like to apply a function that takes the values of three columns and computes the minimum difference between the three values. #dataset df <- data.frame(a= sample(1:...
zach's user avatar
  • 30.4k
34 votes
3 answers
47k views

Loop over rows of dataframe applying function with if-statement

I'm new to R and I'm trying to sum 2 columns of a given dataframe, if both the elements to be summed satisfy a given condition. To make things clear, what I want to do is: > t.d<-as.data.frame(...
Elinka's user avatar
  • 343
34 votes
1 answer
28k views

Applying a function to two lists?

To find the row-wise correlation of two matrices X and Y, the output should have a correlation value for row 1 of X and row 1 of Y, ..., hence in total ten values (because there are ten rows): X <-...
Paul's user avatar
  • 1,107
34 votes
2 answers
34k views

How do I run apply on a data.table?

I have a data.table with columns 2 through 20 as strings with spaces (e.g., "Species Name"). I want to run str_replace() on all those columns simultaneously so all the "Species Name" become "...
Maiasaura's user avatar
  • 32.6k
33 votes
3 answers
18k views

what's the difference between 'call/apply' and 'bind' [duplicate]

var obj = { x: 81, getX: function() { console.log( this.x) } }; var getX = obj.getX.bind(obj);//use obj as 'this'; getX();//81 var getX = function(){ obj.getX.apply(obj); } getX();//...
bennyrice's user avatar
  • 333
33 votes
3 answers
27k views

How to use pandas to find consecutive same data in time series

Here is a time series data like this,call it df: 'No' 'Date' 'Value' 0 600000 1999-11-10 1 1 600000 1999-11-11 1 2 600000 1999-11-12 1 3 600000 ...
figo's user avatar
  • 333
33 votes
5 answers
29k views

Row/column counter in 'apply' functions

What if one wants to apply a functon i.e. to each row of a matrix, but also wants to use as an argument for this function the number of that row. As an example, suppose you wanted to get the n-th root ...
Brani's user avatar
  • 6,624
32 votes
2 answers
95k views

Pandas Rolling Apply custom

I have been following a similar answer here, but I have some questions when using sklearn and rolling apply. I am trying to create z-scores and do PCA with rolling apply, but I keep on getting 'only ...
Bobe Kryant's user avatar
  • 2,050
31 votes
4 answers
11k views

Apply list of functions to list of values

In reference to this question, I was trying to figure out the simplest way to apply a list of functions to a list of values. Basically, a nested lapply. For example, here we apply sd and mean to ...
BrodieG's user avatar
  • 52.3k
29 votes
2 answers
20k views

how to access global/outer scope variable from R apply function?

I can't seem to make apply function access/modify a variable that is declared outside... what gives? x = data.frame(age=c(11,12,13), weight=c(100,105,110)) x testme <- function(df) { ...
fatdragon's user avatar
  • 2,259

1
2 3 4 5
120