转换为字符串后如何保留空值?我正在处理社会安全号码,有必要在浮点数和字符串之间来回切换。
import pandas as pd
import numpy as np
x = pd.Series([np.nan, 123., np.nan, 456.], dtype = float)
x.isnull()
Run Code Online (Sandbox Code Playgroud)
...有空值
y = x.astype(str)
y.isnull()
Run Code Online (Sandbox Code Playgroud)
...没有空值
So ideally x.isnull() and y.isnull() would be the same.
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 …Run Code Online (Sandbox Code Playgroud)