python - 在 Pandas 中将 IP 地址转换为整数

标签 python pandas integer ip-address

我有一个 Pandas 数据框,如下所示,我正在尝试将 IP 地址转换为整数。

    install Network subnet_bits Next    Hop AS1 AS2 AS3 AS4 
0   *   1.0.0.0 24.0    202.12.28.1 0   4777    13335   i   NaN NaN 
1   *   1.0.4.0 22.0    202.12.28.1 0   4777    6939    4826    38803   56203
2   *   1.0.4.0 24.0    202.12.28.1 0   4777    6939    4826    38803   56203   

我正在使用ipaddress库。看来索引正在妨碍。我不知道如何轻松地将 UP 地址转换为整数。

这是我的代码:

try:
    network = int(ipaddress.IPv4Address(df['Network']))
    print(network)
except ValueError:
    print('address/netmask is invalid for IPv4:', df.Network)

这是错误消息:

address/netmask is invalid for IPv4: 

0             1.0.0.0
1             1.0.4.0
2             1.0.4.0

最佳答案

我认为您的问题是 ipaddress.IPv4Address 不支持列上的向量操作。

试试这个:

df['int_network'] = df['Network'].apply(lambda x: int(ipaddress.IPv4Address(x)))

此外,请确保在调试时在 try, catch 中打印出原始错误消息和堆栈跟踪。

关于python - 在 Pandas 中将 IP 地址转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59023756/

相关文章:

Python-类型错误 : 'NoneType' object is not subscriptable

python - 读取 .csv 文件并跳过 Python 2.4.3 中的第一行的命令是什么

python-3.x - 删除 Pandas 数据框中的小数列

python - 需要整数吗?打开()

Python 作业 - 没有意义

python - 访问不同 block 的 Jinja 宏

python - 在Python中高精度地找到由(x,y)数据给出的两条曲线的交点

python - Pandas 输出空列

python - 我无法使用 pip 安装任何软件包

java - 对于循环整数和字符串变量?