数据分析 | 频率编码和标签编码 | Python代码

数据集见GitHub链接:https://github.com/ChuanTaoLai/Frequency-Encoding-And-Label-Encoding

标签编码:

python 复制代码
import pandas as pd
from sklearn.preprocessing import LabelEncoder

data1 = pd.read_excel(r'D:\0文献整理\网络入侵检测\KDD99\KDDTrain.xlsx')
data2 = pd.read_excel(r'D:\0文献整理\网络入侵检测\KDD99\KDDTest_without_unkown.xlsx')

'''标签编码'''
label_encoder = LabelEncoder()
df1 = pd.DataFrame()
df2 = pd.DataFrame()

df1['Attack_Types'] = label_encoder.fit_transform(data1['Attack_Types'])
df2['Attack_Types'] = label_encoder.transform(data2['Attack_Types'])

df1.to_excel('KDDTrain_label_encoded.xlsx', index=False)
df2.to_excel('KDDTest_label_encoded.xlsx', index=False)

频率编码:

python 复制代码
import pandas as pd

data1 = pd.read_excel(r'D:\0文献整理\网络入侵检测\KDD99\KDDTrain.xlsx')
data2 = pd.read_excel(r'D:\0文献整理\网络入侵检测\KDD99\KDDTest_without_unkown.xlsx')

df1 = data1[['protocol_type', 'service', 'flag']].copy()
df2 = data2[['protocol_type', 'service', 'flag']].copy()

'''频率编码'''
for col in df1.columns:
    df1[col + '_frequency_encoded'] = df1[col].map(df1[col].value_counts(normalize=True))

for col in df2.columns:
    df2[col + '_frequency_encoded'] = df2[col].map(df2[col].value_counts(normalize=True))

df1.to_excel('KDDTrain_frequency_encoded.xlsx', index=False)
df2.to_excel('KDDTest_frequency_encoded.xlsx', index=False)
相关推荐
AI攻城狮2 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽2 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
哥布林学者14 小时前
高光谱成像(一)高光谱图像
机器学习·高光谱成像
罗西的思考16 小时前
AI Agent框架探秘:拆解 OpenHands(10)--- Runtime
人工智能·算法·机器学习
孟健17 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
HXhlx19 小时前
CART决策树基本原理
算法·机器学习
码路飞19 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程1 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python