0

Goal is to apply a conditional function on a specific subset of a pandas dataframe. I kept getting error showing "('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index C')"

Dataframe:

import numpy as np
import pandas as pd


df1 = pd.DataFrame(np.arange(0,30).reshape(6,5),'row1 row2 row3 row4 row5 row6'.split(),'A B C D E'.split())  
df1


        A   B   C   D   E
row1    0   1   2   3   4
row2    5   6   7   8   9
row3    10  11  12  13  14
row4    15  16  17  18  19
row5    20  21  22  23  24
row6    25  26  27  28  29

Here is the function I tried

def func (x):
    if x <10:
        return "fit"
    else:
        return x + 10

df1.iloc[[1,2],[2,3]] = df1.iloc[[1,2],[2,3]].apply(func)

But then I keep getting error

cs95
  • 379,657
  • 97
  • 704
  • 746
thegeek
  • 19
  • 3

1 Answers1

0

Try applymap on the subset of the dataframe instead:

df_sub=df1.iloc[[1,2],[2,3]]
df_sub=df_sub.applymap(func)
Nev1111
  • 1,039
  • 9
  • 13
  • 1
    can you tell why my way of doing that doesn't work ? – thegeek May 01 '19 at 18:25
  • From what I know and I think there’s a lot more to this, apply works on the row/column, while applymap works element-wise. There’s a good discussion on the topic in this thread: https://stackoverflow.com/questions/19798153/difference-between-map-applymap-and-apply-methods-in-pandas – Nev1111 May 01 '19 at 18:35