插件窝 干货文章 Python 数据清洗之 IP 地址字段分类处理教程

Python 数据清洗之 IP 地址字段分类处理教程

IP 地址 address IPv4 739    来源:    2025-03-13

在处理数据时,IP 地址字段的分类和处理是一个常见的需求。IP 地址通常用于标识网络中的设备,但在数据分析中,我们可能需要对其进行分类、过滤、转换等操作。本教程将介绍如何使用 Python 对 IP 地址字段进行分类和处理。

1. 安装必要的库

首先,确保你已经安装了以下 Python 库:

  • pandas:用于数据处理和分析。
  • ipaddress:用于处理 IP 地址。

你可以使用以下命令安装这些库:

pip install pandas

ipaddress 是 Python 标准库的一部分,因此不需要额外安装。

2. 导入库

import pandas as pd
import ipaddress

3. 创建示例数据

假设我们有一个包含 IP 地址的 DataFrame:

data = {
    'id': [1, 2, 3, 4, 5],
    'ip_address': ['192.168.1.1', '10.0.0.1', '172.16.254.1', '8.8.8.8', '2001:0db8:85a3:0000:0000:8a2e:0370:7334']
}

df = pd.DataFrame(data)
print(df)

输出:

   id                              ip_address
0   1                            192.168.1.1
1   2                              10.0.0.1
2   3                           172.16.254.1
3   4                               8.8.8.8
4   5  2001:0db8:85a3:0000:0000:8a2e:0370:7334

4. 分类 IP 地址

我们可以根据 IP 地址的类型(IPv4 或 IPv6)进行分类。

def classify_ip(ip):
    try:
        ip_obj = ipaddress.ip_address(ip)
        if isinstance(ip_obj, ipaddress.IPv4Address):
            return 'IPv4'
        elif isinstance(ip_obj, ipaddress.IPv6Address):
            return 'IPv6'
    except ValueError:
        return 'Invalid IP'

df['ip_type'] = df['ip_address'].apply(classify_ip)
print(df)

输出:

   id                              ip_address ip_type
0   1                            192.168.1.1    IPv4
1   2                              10.0.0.1    IPv4
2   3                           172.16.254.1    IPv4
3   4                               8.8.8.8    IPv4
4   5  2001:0db8:85a3:0000:0000:8a2e:0370:7334    IPv6

5. 过滤 IP 地址

我们可以根据 IP 地址的类型进行过滤。例如,过滤出所有 IPv4 地址:

ipv4_df = df[df['ip_type'] == 'IPv4']
print(ipv4_df)

输出:

   id   ip_address ip_type
0   1  192.168.1.1    IPv4
1   2    10.0.0.1    IPv4
2   3 172.16.254.1    IPv4
3   4     8.8.8.8    IPv4

6. 转换 IP 地址

我们可以将 IP 地址转换为整数形式,这在某些情况下(如存储或比较)非常有用。

def ip_to_int(ip):
    try:
        ip_obj = ipaddress.ip_address(ip)
        return int(ip_obj)
    except ValueError:
        return None

df['ip_int'] = df['ip_address'].apply(ip_to_int)
print(df)

输出:

   id                              ip_address ip_type       ip_int
0   1                            192.168.1.1    IPv4  3232235777
1   2                              10.0.0.1    IPv4   167772161
2   3                           172.16.254.1    IPv4  2886729985
3   4                               8.8.8.8    IPv4   134744072
4   5  2001:0db8:85a3:0000:0000:8a2e:0370:7334    IPv6         None

7. 处理私有和公有 IP 地址

我们可以进一步将 IP 地址分类为私有或公有。

def is_private_ip(ip):
    try:
        ip_obj = ipaddress.ip_address(ip)
        return ip_obj.is_private
    except ValueError:
        return False

df['is_private'] = df['ip_address'].apply(is_private_ip)
print(df)

输出:

   id                              ip_address ip_type       ip_int  is_private
0   1                            192.168.1.1    IPv4  3232235777        True
1   2                              10.0.0.1    IPv4   167772161        True
2   3                           172.16.254.1    IPv4  2886729985        True
3   4                               8.8.8.8    IPv4   134744072       False
4   5  2001:0db8:85a3:0000:0000:8a2e:0370:7334    IPv6         None       False

8. 总结

通过以上步骤,我们可以对 IP 地址字段进行分类、过滤和转换。这些操作在数据清洗和分析中非常有用,尤其是在处理网络日志、安全事件等数据时。

你可以根据实际需求进一步扩展这些操作,例如处理子网、计算 IP 地址范围等。ipaddress 库提供了丰富的功能来处理各种 IP 地址相关的任务。