我在pandas数据框中有一列非常大的电话号码,并且它们都是浮点格式:3.52831E+11
。还存在NaN。
我正在尝试将数字转换为int,并且抛出一个错误,即NaNs无法转换为int。很公平。但是我似乎无法解决这个问题。
这里是一个示例:
df = pd.DataFrame({'number':['3.578724e+11','3.568376e+11','3.538884e+11',np.NaN]})
number
0 3.578724e+11
1 3.568376e+11
2 3.538884e+11
3 NaN
# My first attempt: here's where I try to convert them to int() however I get 'cannot convert float NaN to integer'.
df['number'] = [int(x) for x in df['number'] if isinstance(x, float)]
# I have also tried the below, but I get SyntaxError: invalid syntax.
df['number'] = [int(x) for x in df['number'] if x not None]
# and then this one, but the error is: TypeError: must be real number, not str
df['number'] = [int(x) for x in df['number'] if not math.isnan(x) and isinstance(x, float)]
我希望能对此提出一些建议。我认为其中至少有一个会起作用。
谢谢大家
答案 0 :(得分:1)
从熊猫0.24+开始,我们有了Nullable Integer Type。第一步是将字符串(对象)转换为float,然后转换为可空的int:
df.astype('float').astype(pd.Int64Dtype())
number
0 357872400000
1 356837600000
2 353888400000
3 NaN
作为简写,您也可以这样做
df.astype('float').astype('Int64')
number
0 357872400000
1 356837600000
2 353888400000
3 NaN
在旧版本中,唯一的选择是删除NaN并进行转换:
df.dropna(subset=['number']).astype({'number':float}).astype({'number':int})
number
0 357872400000
1 356837600000
2 353888400000