如何在一行代码内将 pandas 中的 float 转换为不包括 NaN 的字符串?

xma*_*man 5 python pandas

我想将一列浮点值转换为字符串,以下是我当前的方式:

userdf['phone_num'] = userdf['phone_num'].apply(lambda x: "{:.0f}".format(x) if x is not None else x)
Run Code Online (Sandbox Code Playgroud)

但是,它还会将 NaN 转换为字符串“nan”,当我检查此列中的缺失值时,这很糟糕,有更好的主意吗?

谢谢!

Arp*_*nki 3

我认为你应该比较 Nan 值而不是比较 None

userdf['phone_num'] = userdf['phone_num'].apply(lambda x: "{:.0f}".
                                          format(x) if not pd.isnull(x) else x)
Run Code Online (Sandbox Code Playgroud)

  • 因此,如果您想要默认值,则可以将其放入上面答案中的 if 条件中。因此,如果值为 NaN,也许您可​​以输入 NA 之类的内容 (2认同)