Iteration over string values with apply()

screen link: https://app.dataquest.io/m/346/working-with-strings-in-pandas/2/using-apply-to-transform-strings

def extract_last_word(element):
    return element.split()[-1]

merged['Currency Apply'] = merged['CurrencyUnit'].apply(extract_last_word)
merged['Currency Apply'].head()

when I run the above code, I am getting:
’float’ object has no attribute 'split’

is this because that pandas cannot iterate over string values, so by accepting string values as float, it can do this task?
I mean that it is like a trick to perform this task .

Could somebody clearly explain this?

Thank you very much in advance!

Actually Pandas can iterate over string values, however the documentation says " Columns with mixed types are stored with the object dtype", so you need to transform each element into a string to be able to use the .split() method

And the instructions are pretty clear by the way
imagen

1 Like

Can you please help me understanding the problem with the below code?

def extract_last_word(element):
    list1=str(element).split()
    return list[-1]

merged['Currency Apply']=merged['CurrencyUnit'].apply(extract_last_word)

It gave me this following error:

TypeErrorTraceback (most recent call last)
in ()
3 return list[-1]
4
----> 5 merged[‘Currency Apply’]=merged[‘CurrencyUnit’].apply(extract_last_word)

/dataquest/system/env/python3/lib/python3.4/site-packages/pandas/core/series.py in apply(self, func, convert_dtype, args, **kwds)
2549 else:
2550 values = self.asobject
-> 2551 mapped = lib.map_infer(values, f, convert=convert_dtype)
2552
2553 if len(mapped) and isinstance(mapped[0], Series):

pandas/_libs/src/inference.pyx in pandas._libs.lib.map_infer()

in extract_last_word(element)
1 def extract_last_word(element):
2 list1=str(element).split()
----> 3 return list[-1]
4
5 merged[‘Currency Apply’]=merged[‘CurrencyUnit’].apply(extract_last_word)

TypeError: ‘type’ object is not subscriptable

Hi,

did you try :

merged['Currency Apply']=[i[-1] for i in merged['CurrencyUnit'].str.split()]

Also your funcion has a typo :

def extract_last_word(element):
   list1=str(element).split()
   return list[-1]

instead of:

def extract_last_word(element):
   list1=str(element).split()
   return list1[-1]

or just one line of code:

def extract_last_word(element):    
   return str(element).split()[-1]

Thanks , It worked !