DataFrame.astype() errors parameter
使用
我试图将大DF中的稀疏列的类型转换(从float到int)。 我的问题是
这是一个玩具示例:
1 2 | t=pd.DataFrame([[1.01,2],[3.01, 10], [np.NaN,20]]) t.astype({0: int}, errors='ignore') |
ValueError: Cannot convert non-finite values (NA or inf) to integer
您可以在熊猫0.24.0+中使用新的可为空的整数dtype。 在使用
1 2 3 4 5 6 7 8 9 10 11 | In [1]: import numpy as np; import pandas as pd; pd.__version__ Out[1]: '0.24.2' In [2]: t = pd.DataFrame([[1.01, 2],[3.01, 10], [np.NaN, 20]]) In [3]: t.round().astype('Int64') Out[3]: 0 1 0 1 2 1 3 10 2 NaN 20 |
试试这个:
1 | t.astype('int64', copy=False, errors='ignore') |
将输出:
1 2 3 4 | 0 1 0 1.01 2 1 3.01 10 2 NaN 20 |
根据文档,这可能是
更新:
1 2 3 | t=pd.DataFrame([[1.01,2],[3.01, 10], [np.NaN,20]], columns=['0', '1']) t.astype({'0': 'int64', '1': 'int64'}, errors='ignore') |
我也尝试向您的数据集添加列名,但是失败了。 可能是一些符号怪癖,错误或就地复制问题。
尝试
1 | t_new=t.mask(t.notnull(),t.values.astype(int)) |
试试这个:
1 2 | out = t.fillna(99999).astype(int) final = out.replace(99999, 'Nan') |
输出:
1 2 3 4 | 0 1 0 1 2 1 3 10 2 Nan 20 |