Pandas:ValueError:无法将float NaN转换为整数

Jaa*_*akL 22 python csv pandas

我得到ValueError:无法将float NaN转换为整数以用于以下内容:

df = pandas.read_csv('zoom11.csv')
df[['x']] = df[['x']].astype(int)
Run Code Online (Sandbox Code Playgroud)
  • "x"显然是csv文件中的一列,但是我无法在文件中发现任何浮动NaN,并且不知道这是什么意思.
  • 当我将列作为String读取时,它的值为-1,0,1,... 2000,对我来说看起来都非常好.
  • 当我将列读取为float时,可​​以加载它.然后它显示值为-1.0,0.0等,仍然没有任何NaN-s
  • 我在read_csv中尝试使用error_bad_lines = False和dtype参数无效.它只是取消加载相同的异常.
  • 该文件不小(超过10行),因此无法手动检查,当我提取一个小的标题部分,然后没有错误,但它发生在完整文件.所以它是文件中的东西,但无法检测到什么.
  • 从逻辑上讲,csv不应该有缺失值,但即使有一些垃圾,我也可以跳过这些行.或至少识别它们,但我没有办法扫描文件并报告转换错误.

更新:使用评论/答案中的提示我将数据清理干净:

# x contained NaN
df = df[~df['x'].isnull()]

# Y contained some other garbage, so null check was not enough
df = df[df['y'].str.isnumeric()]

# final conversion now worked
df[['x']] = df[['x']].astype(int)
df[['y']] = df[['y']].astype(int)
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 26

要识别NaN值,请使用boolean indexing:

print(df[df['x'].isnull()])
Run Code Online (Sandbox Code Playgroud)

然后删除所有非数值使用to_numericparameetr errors='coerce'- 它将非数字替换为NaNs:

df['x'] = pd.to_numeric(df['x'], errors='coerce')
Run Code Online (Sandbox Code Playgroud)

并删除了所有行NaNS IN列x使用dropna:

df = df.dropna(subset=['x'])
Run Code Online (Sandbox Code Playgroud)

最后转换为ints的值:

df['x'] = df['x'].astype(int)
Run Code Online (Sandbox Code Playgroud)

  • 你可能看到了,因为 python 将 `'-1'` 解释为一个字符串,它不是一个数字 (3认同)

cs9*_*s95 20

ValueError:无法将浮点 NaN 转换为整数

从 v0.24 开始,您实际上可以。Pandas 引入了Nullable Integer 数据类型,它允许整数与 NaN 共存。

给定一系列缺失数据的整浮点数,

s = pd.Series([1.0, 2.0, np.nan, 4.0])
s

0    1.0
1    2.0
2    NaN
3    4.0
dtype: float64

s.dtype
# dtype('float64')
Run Code Online (Sandbox Code Playgroud)

您可以将其转换为可为空的 int 类型(从Int16Int32、 或之一中选择Int64),

s2 = s.astype('Int32') # note the 'I' is uppercase
s2

0      1
1      2
2    NaN
3      4
dtype: Int32

s2.dtype
# Int32Dtype()
Run Code Online (Sandbox Code Playgroud)

您的专栏需要有整数才能进行演员表。其他任何事情都会引发 TypeError:

s = pd.Series([1.1, 2.0, np.nan, 4.0])

s.astype('Int32')
# TypeError: cannot safely cast non-equivalent float64 to int32
Run Code Online (Sandbox Code Playgroud)

  • 我收到一条错误消息“TypeError:对象无法转换为 IntegerDtype”,您知道这意味着什么吗? (4认同)

Lui*_*obo 17

另外,即使在最新版本的 pandas 中,如果列是对象类型,您也必须首先转换为浮点数,例如:

df['column_name'].astype(np.float).astype("Int32")
Run Code Online (Sandbox Code Playgroud)

注意:出于某种原因,您必须首先遍历 numpy float,然后再遍历可为空的 Int32。

int 的大小(如果是 32 或 64)取决于您的变量,请注意,如果您的数字对于格式来说太大,您可能会失去一些精度。


Mat*_* W. 5

我知道这已得到解答,但希望将来为任何人提供替代解决方案:

您可以使用.loc仅按 的值对数据帧进行子集化notnull(),然后'x'仅对列进行子集化。使用相同的向量,并apply(int)对其进行处理。

如果列 x 是浮动的:

df.loc[df['x'].notnull(), 'x'] = df.loc[df['x'].notnull(), 'x'].apply(int)
Run Code Online (Sandbox Code Playgroud)