擅长:python、mysql、java
<blockquote>
<h1>ValueError: cannot convert float NaN to integer</h1>
</blockquote>
<p>从v0.24开始,你实际上可以。Pandas引入了<a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html#nullable-integer-data-type" rel="noreferrer">Nullable Integer Data Types</a>,允许整数与NaNs共存。</p>
<p>给定一系列缺少数据的全浮点数</p>
<pre><code>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')
</code></pre>
<p>您可以使用以下命令将其转换为可为空的int类型(从<code>Int16</code>、<code>Int32</code>或<code>Int64</code>中选择一个)</p>
<pre><code>s2 = s.astype('Int32') # note the 'I' is uppercase
s2
0 1
1 2
2 NaN
3 4
dtype: Int32
s2.dtype
# Int32Dtype()
</code></pre>
<p>你的专栏需要有完整的数字,才能进行演员阵容。任何其他操作都会引发类型错误:</p>
<pre><code>s = pd.Series([1.1, 2.0, np.nan, 4.0])
s.astype('Int32')
# TypeError: cannot safely cast non-equivalent float64 to int32
</code></pre>