0

I have a dataframe

df = pd.DataFrame({
    'a': [-1.5, 2.5, 2.0],
    'b': [0.25, -2.75, 3.5],
    'c': [1.25, -0.75, 2.0]
})
    a     b     c

  -1.5  0.25  1.25

   2.5 -2.75 -0.75

   2.0  3.50  2.00

I want to create a new dataframe 'df_fun' by applying the below function on 'df'.

def fun(x):
  if (x < 0) :
    return 1
  else :
    return 2*x

df_fun = df.apply(fun, axis = 1)

However, I’m getting the below error.

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Appreciate the answers/responses.

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
mnr
  • 55
  • 5
  • 2
    Does this answer your question? [Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()](https://stackoverflow.com/questions/36921951/truth-value-of-a-series-is-ambiguous-use-a-empty-a-bool-a-item-a-any-o) – Alan Bagel Jul 08 '21 at 20:20
  • Very similar to [Pandas apply custom function to DF](https://stackoverflow.com/q/68274975/15497888), `applymap` would work here as well. – Henry Ecker Jul 08 '21 at 20:25
  • 1
    `df_fun = df.applymap(lambda x: fun(x))` EDIT: thanks to @HenryEcker who already mentioned it – zswqa Jul 08 '21 at 20:36
  • 1
    No need for the lambda @zswqa `df_fun = df.applymap(fun)` – Henry Ecker Jul 08 '21 at 20:37
  • 1
    Hi @HenryEcker, applymap worked like a charm. Thanks for your quick response. – mnr Jul 08 '21 at 20:39

0 Answers0