【发布时间】:2020-11-04 10:38:08
【问题描述】:
我有一个数组x,其中一个值是NaN。
x = [1, 2, NaN, 3, 5]
除了NaN,所有元素都是整数。
该数组类型被视为 float64 而不是 int。
我想将类型从浮动转换为字符串。
我试过astype(str)。但这会产生小数点,例如x = [1.0, 2.0, NaN, 3.0, 5.0]
我试过astype(int).astype(str)。但是,在这种情况下,由于 NaN 元素,它不起作用。
那么,我如何将带有一些元素为 NaN 的整数数组转换为不带小数点的字符串类型?
感谢您的阅读。
import numpy as np
import pandas as pd
df = pd.DataFrame({'x' : [1,2, np.nan ,3,5]})
# df.dtypes
df['x'] = df['x'].astype(str)
# In this case, it make decimal point.
df['x'] = df['x'].astype(int).astype(str)
# It doesn't work due to NaN element.
【问题讨论】:
标签: python python-3.x pandas numpy