数据分析 | 频率编码和标签编码 | 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)
相关推荐
ragnwang1 天前
Notes: Python pybind11 import C++ module
开发语言·c++·python
王中阳Go1 天前
后端转 Agent 岗面试怎么答:8 个高频问题与应答口径
人工智能·后端·python·大语言模型
weixin_307779131 天前
RAG 面试陷阱——混合检索并非无条件优越:一个条件反转实验
人工智能·python·面试·职场和发展
云和数据.ChenGuang1 天前
深入解析 Python 的 dir():从用法到 CPython 源码实现
开发语言·人工智能·python·langchain
我要见SA姐11 天前
GitHub Actions 自动化:5 个真实运维提效案例
运维·数据库·机器学习·oracle·回归
荣码1 天前
长上下文与大文档处理:200页PDF怎么喂给AI,我踩了4个坑
java·python
遇码1 天前
2026-11-01-daw-retry-banner-body
人工智能·ai·rust·数据分析·大模型·agent
Zzj_tju1 天前
智能体该向哪段经验学习?Routed CL 在混合任务中探索记忆分流
人工智能·深度学习·机器学习·语言模型
databook1 天前
Pandas 与 Polars:语法、性能和资源占用方面的对比
python·数据分析·pandas
威哥爱编程1 天前
Python 智能体开发实战 10:本地跑得好好的,一并发就崩?把它做成一个能上线的服务
python·agent