[英]Pandas: ValueError: cannot convert float NaN to integer
我得到ValueError: cannot convert float NaN to integer for following:
df = pandas.read_csv('zoom11.csv')
df[['x']] = df[['x']].astype(int)
更新:使用評論/答案中的提示,我用這個清理了我的數據:
# 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)
要識別NaN
值,請使用boolean indexing
:
print(df[df['x'].isnull()])
然后刪除所有非數字值使用to_numeric
和參數errors='coerce'
- 將非數字值替換為NaN
s:
df['x'] = pd.to_numeric(df['x'], errors='coerce')
要刪除x
列中帶有NaN
的所有行,請使用dropna
:
df = df.dropna(subset=['x'])
最后將值轉換為int
s:
df['x'] = df['x'].astype(int)
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')
您可以將其轉換為可為空的 int 類型(從Int16
、 Int32
或Int64
之一中選擇),
s2 = s.astype('Int32') # note the 'I' is uppercase
s2
0 1
1 2
2 NaN
3 4
dtype: Int32
s2.dtype
# Int32Dtype()
您的專欄需要有整數才能進行演員表。 其他任何事情都會引發 TypeError:
s = pd.Series([1.1, 2.0, np.nan, 4.0])
s.astype('Int32')
# TypeError: cannot safely cast non-equivalent float64 to int32
此外,即使在最新版本的熊貓中,如果列是對象類型,您也必須先轉換為浮點數,例如:
df['column_name'].astype(np.float).astype("Int32")
注意:出於某種原因,您必須先通過 numpy float 再到可空 Int32。
int 的大小(如果是 32 或 64)取決於您的變量,請注意,如果您的數字對於格式來說太大,您可能會失去一些精度。
我知道這已得到解答,但希望將來為任何人提供替代解決方案:
您可以使用.loc
僅按notnull()
值對數據幀進行子集化,然后僅對'x'
列進行子集化。 取相同的向量,然后對其apply(int)
。
如果列 x 是浮動的:
df.loc[df['x'].notnull(), 'x'] = df.loc[df['x'].notnull(), 'x'].apply(int)
如果你有空值那么在做數學運算你會得到這個錯誤來解決它使用df[~df['x'].isnull()]df[['x']].astype(int)
如果你想要你的數據集不可更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.