0

I'm trying to write a lambda-function into a def:-function in order to better understand what is going on in a Python example-script I got. In some function in that script a lambda-function is integrated and I'm wondering what it would look like as def:-statement. (I'm new to using lamda functions) So here is the code:

import numpy as np
import pandas as pd

df = pd.DataFrame({"A": [18,28,29,32,35,36,37,37,39,40,42,42,46,48,54,56,57,61,61,62,63,65],                  "B":  [9,13,17,15,23,21,24,28,26,30,29,36,38,42,40,48,40,51,54,50,51,57]})

a = lambda df: np.corrcoef(df[:,0], df[:,1])[0,1]
print(a)

>>>function <lambda> at 0x0000016896784950> #result of print-statement

def lamb(df):
    g = np.corrcoef(df.iloc[:,0],df.iloc[:,1])[0,1]
    return g

b = lamb(df)
print(b)

>>>0.974499725153725 #result of print-statement

How do I alter the def lamb(df):-code so that its print-statement has the same output as the print-statement of the lambda-function?

7
  • 1
    You are not printing the same, in one your are printing a lambda function object and in the the other the result of a function call Commented Apr 18, 2020 at 17:53
  • I know, that's my question. How do I alter the 'def lamb(df):'-function in order that it prints the same.. Commented Apr 18, 2020 at 17:55
  • 1
    Just: print(a(df)) in the same way you had print(lamb(df)). Both a and lamb are functions. Commented Apr 18, 2020 at 17:57
  • 2
    print(lamb) ? Commented Apr 18, 2020 at 17:58
  • print(a(df)) gives: TypeError: '(slice(None, None, None), 0)' is an invalid key Commented Apr 18, 2020 at 17:59

3 Answers 3

2

print(a) prints a function, but

b = lamb(df)
        
print(b)

print the output of the function

Try print(lamb) to get the similar result

Sign up to request clarification or add additional context in comments.

1 Comment

Jep, that's it! Damn.
1

With

print(a)

You're trying to print a function, to have the same usable output:

print(a(df))

Is what you're looking for

2 Comments

print(a(df)) gives: TypeError: '(slice(None, None, None), 0)' is an invalid key
Can be a conflict in naming, what happens when you change either the variable name or the parameter in your lambda declaration?
0

just print the function lamb. this will print the function at location at 0x......

print(lamb)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.