1

This is a follow up question I read just now : DataFrame, apply, lambda, list comprehension.

So I tried the following code

import pandas as pd

# This is a dataframe containing the correct values
correct = pd.DataFrame([{"letters":"abc","data":1},{"letters":"ast","data":2},{"letters":"bkgf","data":3}])

# This is the dataframe containing source data
source = pd.DataFrame([{"c":"ab"},{"c":"kh"},{"c":"bkg"}])

temp_result = source["c"].apply(lambda x: i for (i,row) in correct.values)

So i tried different variations like this

temp_result = source["c"].apply(lambda x: i for (i,row) in correct.iteritems())

Yet all return the error :Genrator object is not callable So my question is why is it returning a generator instead of treating it as a list of items ? I know what generator expressions are, but I am not able to understand why this expression is being treated as a generator instead of a list comprehension (or a lambda expression )?

Gambit1614
  • 8,547
  • 1
  • 25
  • 51
  • 1
    Currently you're passing a generator to apply. If you meant that to be a lambda *returning* a generator, you need to add parentheses. – jonrsharpe Jul 04 '18 at 20:17
  • @jonrsharpe Sorry I am not exactly sure where to add the paranthesis since I think the lambda syntax will become incorrect ? Can you please give an example or show the correct expression :) – Gambit1614 Jul 04 '18 at 20:19
  • `lambda x: (...)`. But it's not clear to me what output you were expecting. – jonrsharpe Jul 04 '18 at 20:19
  • 1
    try `lambda x: [i for (i,row) in correct.iteritems()]` – fafl Jul 04 '18 at 20:20

1 Answers1

1

list comprehensions have the [] square brackets. if you don't have the [] square brackets, you have a generator expression

.apply(lambda x: (i for (i,row) in correct.iteritems())) 

The code above would make a function that returns a generator expression, and pass it to the .apply

.apply([lambda x: i for (i,row) in correct.iteritems()]) 

The code above would create a list of functions, and pass that list to .apply

.apply(lambda x: [i for (i,row) in correct.iteritems()]) 

The code above would make a function that returns a list, and pass it to the .apply.

nosklo
  • 217,122
  • 57
  • 293
  • 297
  • So there is no way to modify this expression so that it contains `lambda` and also a list comprehension ? – Gambit1614 Jul 04 '18 at 20:20
  • if you really want list comprehension, you have to add square brackets. Otherwise you can't make a list comprehension. @MohammedKashif – nosklo Jul 04 '18 at 20:22
  • Thanks! it worked :) I actually didn't knew about this case of `apply` and `generators`. Learned something new today :) – Gambit1614 Jul 04 '18 at 20:22
  • The list comprehension of lambdas probably won't behave as expected, see e.g. https://stackoverflow.com/a/34021333/3001761 – jonrsharpe Jul 04 '18 at 20:29