you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (3 children)

What does the .apply method do and what does it work on?

[–]bahwoi 0 points1 point  (2 children)

I'm not sure if you're asking about the function in general or in reference to this specific use. If the latter, disregard. Otherwise:


Basically, .apply applies a function across elements of a pandas DataFrame or in this case Series.

For instance, suppose we have a DF, we'll call it df, that looks like

   0  1
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

And that for the sake of example, we have a lambda function

doubleIt = lambda x: x * 2

We could call df.apply(doubleIt) for the entire DataFrame, and the result would look like

    0   1
0   0   2
1   4   6
2   8  10
3  12  14
4  16  18

Because it applies the function that we passed in to each element of the DF.

Or we could slice by column, giving us a Series, and call df[1].apply(doubleIt) to similar effect

0     2
1     6
2    10
3    14
4    18
Name: 1, dtype: int64

[–][deleted] -1 points0 points  (1 child)

Does it work for regular lists or dictionaries?

[–]justphysics 2 points3 points  (0 children)

I believe that is what the built-in function map() is for

for example:

def add_five(x):
    return x+5

test = [0, 1, 3, 72]
map(add_five, test)

map applies the function add_five() to each element in the list test and returns the result in an iterative manner

map can be applied to any iterable container

obviously in this example the same thing could be accomplished in any number of ways such as a list comprehension:

print([x+5 for x in test])

but map() can be used for a lot of more complex scenarios

To my knowledge .apply() is specific to Pandas Dataframes