0

I have a function:

def lookup(group, name):
    try:
        #sql query with group and name
        return answer
    except:
        return 'NULL'

And a pandas Dataframe:

+------------+------+
|   group    | name |
+------------+------+
| redteam    | paul |
| blueteam   | pat  |
| yellowteam | mike |
+------------+------+

I want to feed the group and name of each row into my 'lookup' function, and return the answer for the row as a cell in a 3rd column: 'value'

I've looked at this and this question. but they're not quite what I'm doing.

I've also looked at THIS question. Which IS what I'm doing. but it also didn't succeed for me.

I've tried this: df['value'] = lookup(df[0],df[1])
and this:
df['value'] = df.apply(lambda x: lookup(x[0], x[1]), axis=1)

but it just makes the value column all 'NULL'

Any suggestions from here are much appreciated.

Community
  • 1
  • 1
singmotor
  • 3,930
  • 12
  • 45
  • 79

1 Answers1

1

It's hard to test without a good reproducible example but you can try this, assuming that group is not the index of the dataframe:

here is a full scale example :

df = pd.DataFrame(np.random.rand(10,2), columns=['group', 'name'])

def lookup(group, name):
    if group > 0.4:
        return 'YES'
    else:
        return 'NULL'

df['value'] = df.apply(lambda x: lookup(x['group'], x['name']), axis=1)

df
      group      name value
0  0.088522  0.221607  NULL
1  0.366478  0.612860  NULL
2  0.018939  0.995080  NULL
3  0.143422  0.590115  NULL
4  0.747373  0.888054   YES
5  0.960380  0.586448   YES
6  0.671776  0.151144   YES
7  0.632334  0.802551   YES
8  0.041953  0.387241  NULL
9  0.557183  0.199470   YES
Steven G
  • 16,244
  • 8
  • 53
  • 77
  • Steven, thanks this worked great! Turns out I was forgetting to pass the cursor to the sql statement, and that's why I was getting the 'NULL' return of the function. That said, I think that now makes this question a duplicate – singmotor May 09 '17 at 18:51