Search code examples
pythonlambdaapplypinyin

why I got an error ''float' object is not iterable' while using apply lambda


I try to convert a list of Chinese province into pinyin use pinyin package, code like below:

df['province'] = df['comb_province'].apply(lambda x: pinyin.get(x, format="strip", delimiter=''))

but I got an error says: 'float' object is not iterable. Why this happens? How can I fix it?

Thank you!


Solution

  • You may have been encountered numpy.nan or None values in the df["comb_province"] column. So, you could try to remove those rows with numpy.nan by using the following code:

    df = df[~df["comb_province"].isnull()]
    

    or if you wish to keep the rows with numpy.nan or None, then using the following:

    df["comb_province"] = df["comb_province"].astype(str)
    

    Your original code may be of strip or split, something related to string operations, which will throw an error when encountering either numpy.nan or None.