Python數(shù)據(jù)分析實戰(zhàn)-數(shù)值型特征和類別型特征歸一化編碼操作(附源碼和實現(xiàn)效果)

實現(xiàn)功能:

Python數(shù)據(jù)分析實戰(zhàn)-數(shù)值型特征和類別型特征歸一化編碼操作

實現(xiàn)代碼:

import pandasas pd

import warnings

warnings.filterwarnings("ignore")

df = pd.read_csv("E:\數(shù)據(jù)雜壇\datasets\kidney_disease.csv")

df=pd.DataFrame(df)

pd.set_option('display.max_rows', None)

pd.set_option('display.width', None)

df.drop("id",axis=1,inplace=True)

print(df.head())

df["classification"] = df["classification"].apply(lambda x: xif x =="notckd" else "ckd")

# 數(shù)值型變量名

num_cols = [colfor colin df.columnsif df[col].dtype !="object"]

# 分類型變量名

cat_cols = [colfor colin df.columnsif df[col].dtype =="object"]

print(df.isnull().sum().sort_values(ascending =False))

# ======================缺失值處理============================

def random_value_imputate(col):

"""

? ? 函數(shù):隨機填充方法(缺失值較多的字段)"""

? ? # 1、確定填充的數(shù)量;在取出缺失值隨機選擇缺失值數(shù)量的樣本

? ? random_sample = df[col].dropna().sample(df[col].isna().sum())

# 2、索引號就是原缺失值記錄的索引號

? ? random_sample.index = df[df[col].isnull()].index

# 3、通過loc函數(shù)定位填充

? ? df.loc[df[col].isnull(), col] = random_sample

def mode_impute(col):

"""

? ? 函數(shù):眾數(shù)填充缺失值"""

? ? # 1、確定眾數(shù)

? ? mode = df[col].mode()[0]

# 2、fillna函數(shù)填充眾數(shù)

? ? df[col] = df[col].fillna(mode)

for colin num_cols:

random_value_imputate(col)

for colin cat_cols:

if colin ['rbc','pc']:

# 隨機填充

? ? ? ? random_value_imputate('rbc')

random_value_imputate('pc')

else:

mode_impute(col)

print(df.isnull().sum().sort_values(ascending =False))

print(df.head())

# ======================特征編碼============================

from sklearn.preprocessingimport MinMaxScaler

mms = MinMaxScaler()

df[num_cols] = mms.fit_transform(df[num_cols])

from sklearn.preprocessingimport LabelEncoder

led = LabelEncoder()

for colin cat_cols:

df[col] = led.fit_transform(df[col])

print(df.head())

實現(xiàn)效果:

本人讀研期間發(fā)表5篇SCI數(shù)據(jù)挖掘相關(guān)論文,現(xiàn)在某研究院從事數(shù)據(jù)挖掘相關(guān)科研工作,對數(shù)據(jù)挖掘有一定認知和理解,會結(jié)合自身科研實踐經(jīng)歷不定期分享關(guān)于python機器學(xué)習(xí)、深度學(xué)習(xí)、數(shù)據(jù)挖掘基礎(chǔ)知識與案例。 致力于只做原創(chuàng),以最簡單的方式理解和學(xué)習(xí),關(guān)注我一起交流成長。 關(guān)注 訂閱號(數(shù)據(jù)雜壇) 可在后臺聯(lián)系我獲取相關(guān)數(shù)據(jù)集和源碼,送有關(guān)數(shù)據(jù)分析、數(shù)據(jù)挖掘、機器學(xué)習(xí)、深度學(xué)習(xí)相關(guān)的電子書籍。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容