繁体   English   中英

熊猫检查哪个子网IP地址属于

[英]Pandas check which subnetwork IP address belongs to

我有一个包含用户及其 IP 地址的 Pandas 数据框:

users_df = pd.DataFrame({'id': [1,2,3],
                         'ip': ['96.255.18.236','105.49.228.135','104.236.210.234']})

   id               ip
0   1    96.255.18.236
1   2   105.49.228.135
2   3  104.236.210.234

以及包含网络范围和相应地理名称 ID 的单独数据框:

geonames_df = pd.DataFrame({'network': ['96.255.18.0/24','105.49.224.0/19','104.236.128.0/17'],
                            'geoname': ['4360369.0','192950.0','5391959.0']})

     geoname           network
0  4360369.0    96.255.18.0/24
1   192950.0   105.49.224.0/19
2  5391959.0  104.236.128.0/17

对于每个用户,我需要针对所有网络检查他们的 ip,并提取相应的 geoname 并将其添加到users_df 我想要这个作为输出:

   id               ip   geonames
0   1    96.255.18.236  4360369.0
1   2   105.49.228.135   192950.0
2   3  104.236.210.234  5391959.0

在这个例子中很简单,因为它们的顺序是正确的,只有 3 个例子。 实际上, users_df有 4000 行,而geonames_df有超过 300 万行

我目前正在使用这个:

import ipaddress

networks = []
for n in geonames_df['network']:
    networks.append(ipaddress.ip_network(n))

geonames = []

for idx, row in users_df.iterrows():
    ip_address = ipaddress.IPv4Address(row['ip'])

    for block in networks:
        if ip_address in block:
            geonames.append(str(geonames_df.loc[geonames_df['network'] == str(block), 'geoname'].item()))
            break

users_df['geonames'] = geonames

由于数据帧/列表上的嵌套循环,这非常慢。 有没有更快的方法来利用 numpy/pandas? 或者至少是某种比上述方法更快的方法?

有一个类似的问题( 如何在 python 2.x 中检查 ip 是否在网络中? ),但是 1)它不涉及 pandas/numpy,2)我想针对多个网络检查多个 IP,以及 3 ) 得票最高的答案无法避免嵌套循环,这就是我性能缓慢的原因

我认为无法避免嵌套循环,但我已将评论中提到的先前解决方案与熊猫结合使用。 您可以检查它是否更快。

import socket,struct

def makeMask(n):
    "return a mask of n bits as a long integer"
    return (2<<n-1) - 1

def dottedQuadToNum(ip):
    "convert decimal dotted quad string to long integer"
    return struct.unpack('L',socket.inet_aton(ip))[0]

def networkMask(network):
    "Convert a network address to a long integer" 
    return dottedQuadToNum(network.split('/')[0]) & makeMask(int(network.split('/')[1]))

def whichNetwork(ip):
    "return the network to which the ip belongs"
    numIp = dottedQuadToNum(ip)
    for index,aRow in geonames_df.iterrows():
        if (numIp & aRow["Net"] == aRow["Net"]):
            return aRow["geoname"]
    return "Not Found"

geonames_df["Net"] = geonames_df["network"].map(networkMask)
users_df["geonames"] = users_df["ip"].map(whichNetwork)

如果你愿意使用 R 而不是 Python,我写了一个ipaddress包可以解决这个问题。 仍然有一个底层循环,但它是用 C++ 实现的(快得多!)

library(tibble)
library(ipaddress)
library(fuzzyjoin)

addr <- tibble(
  id = 1:3,
  address = ip_address(c("96.255.18.236", "105.49.228.135", "104.236.210.234"))
)
nets <- tibble(
  network = ip_network(c("96.255.18.0/24", "105.49.224.0/19", "104.236.128.0/17")),
  geoname = c("4360369.0", "192950.0", "5391959.0")
)

fuzzy_left_join(addr, nets, c("address" = "network"), is_within)
#> # A tibble: 3 x 4
#>      id         address          network geoname  
#>   <int>       <ip_addr>       <ip_netwk> <chr>    
#> 1     1   96.255.18.236   96.255.18.0/24 4360369.0
#> 2     2  105.49.228.135  105.49.224.0/19 192950.0 
#> 3     3 104.236.210.234 104.236.128.0/17 5391959.0

reprex 包(v0.3.0) 于 2020 年 9 月 2 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM