whytheq whytheq - 3 months ago 7
Python Question

Why is apply not being applied

I have this initial dataframe:

df = pd.DataFrame(data = {'colX': ['TQ95','SM90','SJ07','SH97','TF28']})


So df is as follows:

colX
0 TQ95
1 SM90
2 SJ07
3 SH97
4 TF28


No I create a very very simple function and apply it to df:

def foo(x):
return x + 'bar'

df.apply(foo)


Returns:

colX
0 TQ95bar
1 SM90bar
2 SJ07bar
3 SH97bar
4 TF28bar


So why does the following:

def bar(x):
if len(x) == 4:
return 'x'
elif len(x) == 6:
return 'y'
else:
return 'z'

df.apply(bar)


Return this?:

colX z
dtype: object


Rather than this?:

colX
0 x
1 x
2 x
3 x
4 x

Jan Jan
Answer

Did you mean:

df['colX'].apply(bar)

Thus, only the length of the column value is checked.
The complete code:

import pandas as pd
def bar(x):
    if len(x) == 4:
        return 'x'
    elif len(x) == 6:
        return 'y'
    else:
        return 'z'

df = pd.DataFrame(data = {'colX': ['TQ95','SM90','SJ07','SH97','TF28']})
df['colX'] = df['colX'].apply(bar)