-1

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!

Qing
  • 63
  • 1
  • 2
  • 8
  • Please supply the expected [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) (MRE). Show where the intermediate results differ from what you expected. We should be able to copy and paste a contiguous block of your code, execute that file, and reproduce your problem along with tracing output for the problem points. This lets us test our suggestions against your test data and desired output. – Prune Feb 09 '21 at 00:37
  • Please [include a minimal data frame](https://stackoverflow.com/questions/52413246/how-to-provide-a-reproducible-copy-of-your-dataframe-with-to-clipboard) as part of your MRE. – Prune Feb 09 '21 at 00:37

1 Answers1

0

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.

abysslover
  • 683
  • 5
  • 14
  • what if I want to keep all the rows even with the nan value? can I add something into the code? I tried add "if x is not None" in the end, but it didn't work.. – Qing Feb 09 '21 at 00:38
  • As you explained, the input dataframe may have None type as well, then try to convert them to `str` type as suggested. – abysslover Feb 09 '21 at 00:43
  • @Qing I would appreciate it if you could accept my solution as an answer if it helped to solve your problem. – abysslover Feb 09 '21 at 01:57