0

trying to get the concept crystallized in my head.

say, you have a dataframe , and one of the columns is 'JobTitle'.

i'm practicing apply, apply(lambda..., etc.

here is what i get:

try 1: sal['JobTitle'].str.upper() -> this works

try 2: sal['JobTitle'].apply(str.upper()) -> this does NOT work

try 3: sal['JobTitle'].apply(lambda title: title.upper()) -> this works

  1. i'm just trying to understand when it's appropriate to use apply vs lambda vs neither.
  2. why does 'try 2' not work? i guess, broadly, i'm trying to understand when to use apply with or without lambda.

thank you.

Narendra Prasath
  • 1,501
  • 1
  • 10
  • 20
aoh003
  • 1
  • General rue: If you don't know why you need them, you don't need them. – Charles Duffy Jul 10 '20 at 14:06
  • ...that said, `apply` _takes a function_ as its argument. `str.upper()` is not something that returns a function. A lambda, by contrast, _is a literal definition of a function_. – Charles Duffy Jul 10 '20 at 14:07
  • In second try you should use `str.upper` instead of `str.upper()`, because when using the brackets you're inserting what the function returns instead of the function itselft – rafasan Jul 10 '20 at 14:08
  • `apply(str.upper)` without the parens, by contrast, will work. – Charles Duffy Jul 10 '20 at 14:09
  • @CharlesDuffy - thanks. try 1 and try 3, you get the same results successfully. try 2, you get an error. just trying to understanding logically why, so when i need to use it again, i dont have to bang my head against the desk. – aoh003 Jul 10 '20 at 14:09
  • `str.upper` is a bit wierd, because it assumes that `title.upper()` is equivalent to `str.upper(title)`. That's not the case if `title` is an instance of a *subclass* of `str`. – chepner Jul 10 '20 at 14:09
  • `str.upper()` is actually trying to **call** `upper` (with no arguments), and pass the return value to `apply`. You can't call `str.upper()` on its own outside of apply, so you can't call it and pass its result to `apply`. – Charles Duffy Jul 10 '20 at 14:10
  • 1
    This is actually a good use case for `operator.methodcaller`; you can write `obj.apply(methodcaller("title"))`. – chepner Jul 10 '20 at 14:10
  • ...to try to clarify what I was saying above: `'some-specific-string'.upper()`, of course, works on its own; but `str.upper()` doesn't, because it expects to operate on an instance, but is being called on the generic string type itself. But if you just refer to `str.upper` with no parens after it, then you're referring to the method itself (instead of the results of a specific invocation of it), and that _method_ can be safely passed to apply, so long as apply is operating over string instances. – Charles Duffy Jul 10 '20 at 14:13
  • wow, this is my first post, and the power of crowd sourcing is awesome! i was wresting with this for an hour and i get the simple and clear answers in real time. thank you! – aoh003 Jul 10 '20 at 14:14

0 Answers0