Python Pandas 系列:将浮点数转换为字符串,保留空值 [英] Python pandas series: convert float to string, preserving nulls

查看:234
本文介绍了Python Pandas 系列:将浮点数转换为字符串,保留空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在转换为字符串后保留空值?我正在处理社会安全号码,需要在浮点数和字符串之间来回切换.

How can I preserve nulls after converting to string? I'm working with social security numbers, where it's necessary to go back and forth between float and string.

import pandas as pd
import numpy as np    
x = pd.Series([np.nan, 123., np.nan, 456.], dtype = float)
x.isnull()

...有空值

y = x.astype(str)
y.isnull()

...没有空值

所以理想情况下 x.isnull() 和 y.isnull() 应该是一样的.

So ideally x.isnull() and y.isnull() would be the same.

我认为使用一系列混合 dtypes 是危险的,但认为这是目前最好的解决方案:

I think it's dangerous to use a Series of mixed dtypes, but thinking this is the best solution for the time being:

z = y.copy()
z[z == 'nan'] = np.nan
z.isnull() # works as desired
type(z[0]) # but has floats for nulls
type(z[1]) # and strings for values

推荐答案

可以强制转换为字符串,条件是不为空.

You can cast to to string, conditional on not being null.

x[x.notnull()] = x.astype(str)

x
Out[32]
0      NaN
1    123.0
2      NaN
3    456.0
dtype: object

x.values
Out[33]: array([nan, '123.0', nan, '456.0'], dtype=object)

x.isnull()
Out[34]
0     True
1    False
2     True
3    False
dtype: bool

这篇关于Python Pandas 系列:将浮点数转换为字符串,保留空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆