所以我有這樣一個資料框架,其中類別特征有浮動值和納米值。我想將所有浮動值轉換為整數。為此我嘗試了
df['category'] = df['category'] 。 apply(lambda x:int(x) if np.isnan(x)==False else x)
不幸的是,這段代碼沒有任何作用。這是為什么呢?我怎樣才能為我自己的目的修改這段代碼呢?
謝謝你
uj5u.com熱心網友回復:
由于整數不能代表None/NaN值,pandas將系列轉換為float64。
import pandas as pd
import numpy as np
df = pd.DataFrame({"A":[0.51,None,8. 0,7,0.0,-89, np.NaN]})
df.A.apply(lambda x: int(x) if not np.isnan(x) else x) .apply(type)
0 <class 'float'>
1 <class 'float'>
2 <class 'float'>
3 <class 'float'>
4 <class 'float'>
5 <class 'float'>
6 <class 'float'>
名稱。A, dtype: object; Name: A, dtype:>
df.A.apply(lambda x: int(x) if not np. isnan(x) else 'FOO').apply(type)
0 <class 'int'>
1 <class 'str'>
2 <class 'int'>
3 <class 'int'>
4 <class 'int'>
5 <class 'int'>
6 <class 'str'>
uj5u.com熱心網友回復:
試試這個。(此代碼將np.nan轉換為zero)
df["category"] = np.nan_to_num(df['category']).astype(int)
示例:
df = pd.DataFrame({"category":[1. 51,None,8.0,7.0,0.0, -89, np.NaN]})
df["category"] = np.nan_to_num(df['category']).astype(int)
print(df["category"])
輸出:
0 1
1 0
2 8 8
3 7
4 0
5 -89
6 0
名稱:類別,dtype:int64
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/333363.html
標籤:
下一篇:如何在精益中使用套接字?
