小编mef*_*ons的帖子

Python Pandas 系列:将浮点数转换为字符串,保留空值

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

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)

python numpy pandas

6
推荐指数
3
解决办法
5751
查看次数

标签 统计

numpy ×1

pandas ×1

python ×1