按ip地址范围过滤Pandas DataFrame

时间:2014-04-10 05:10:47

标签: python pandas dataframe ip-address

我需要按ip地址范围过滤pandas Dataframe。是否可以使用正则表达式?

Ex. From 61.245.160.0   To 61.245.175.255

3 个答案:

答案 0 :(得分:6)

字符串可以在python中订购,所以你应该能够逃脱:

In [11]: '61.245.160.0' < '61.245.175.255'
Out[11]: True

布尔掩码:

In [12]: df[('61.245.160.0' < df.ip) & (df.ip < '61.245.175.255')]

或切片(如果ip是索引):

In [13]: df.loc['61.245.160.0':'61.245.175.255']

答案 1 :(得分:1)

我有一种使用ipaddress的方法。

例如,我想知道host0 = 10.2.23.5是否属于以下任何一种网络NETS = ['10.2.48.0/25','10.2.23.0/25','10.2.154.0/24']

>>> host0 = ip.IPv4Address('10.2.23.5')
>>> NETS = ['10.2.48.0/25','10.2.23.0/25','10.2.154.0/24']
>>> nets  = [ip.IPv4Network(x) for x in NETS]
>>> [x for x in nets if (host2 >= x.network_address and host2 <= x.broadcast_address)]
[IPv4Network('10.2.23.0/25')]

现在,为了将此方法与Pandas结合在一起,我们应该执行以下操作:创建一个函数并将其应用于DF的每一行。

def fnc(row):
    host = ip.IPv4Address(row)
    vec = [x for x in netsPy if (host >= x.network_address and host <= x.broadcast_address)]

    if len(vec) == 0:
        return '1'
    else:
        return '-1'

您稍后将其应用于DF。

df['newCol'] = df['IP'].apply(fnc)

这会创建一个新列newCol,其中每一行都是1-1,具体取决于IP地址是否属于您感兴趣的网络。

答案 2 :(得分:0)

假设你有以下DF:

In [48]: df
Out[48]:
               ip
0    61.245.160.1
1  61.245.160.100
2  61.245.160.200
3  61.245.160.254

让我们找到介于61.245.160.9961.245.160.254之间的所有IP:

In [49]: ip_from = '61.245.160.99'

In [50]: ip_to = '61.245.160.254'

如果我们将IP作为字符串进行比较 - 它将按字典顺序进行比较,以便它不会像@adele has pointed out那样正常工作:

In [51]: df.query("'61.245.160.99' < ip < '61.245.160.254'")
Out[51]:
Empty DataFrame
Columns: [ip]
Index: []

In [52]: df.query('@ip_from < ip < @ip_to')
Out[52]:
Empty DataFrame
Columns: [ip]
Index: []

我们可以使用numerical IP representation

In [53]: df[df.ip.apply(lambda x: int(IPAddress(x)))
   ....:      .to_frame('ip')
   ....:      .eval('{} < ip < {}'.format(int(IPAddress(ip_from)),
   ....:                                  int(IPAddress(ip_to)))
   ....:       )
   ....: ]
Out[53]:
               ip
1  61.245.160.100
2  61.245.160.200

说明:

In [66]: df.ip.apply(lambda x: int(IPAddress(x)))
Out[66]:
0    1039507457
1    1039507556
2    1039507656
3    1039507710
Name: ip, dtype: int64

In [67]: df.ip.apply(lambda x: int(IPAddress(x))).to_frame('ip')
Out[67]:
           ip
0  1039507457
1  1039507556
2  1039507656
3  1039507710

In [68]: (df.ip.apply(lambda x: int(IPAddress(x)))
   ....:    .to_frame('ip')
   ....:    .eval('{} < ip < {}'.format(int(IPAddress(ip_from)),
   ....:                               int(IPAddress(ip_to))))
   ....: )
Out[68]:
0    False
1     True
2     True
3    False
dtype: bool

PS这里有一个更快(矢量化)的函数,它将返回数字IP表示:

def ip_to_int(ip_ser):
    ips = ip_ser.str.split('.', expand=True).astype(np.int16).values
    mults = np.tile(np.array([24, 16, 8, 0]), len(ip_ser)).reshape(ips.shape)
    return np.sum(np.left_shift(ips, mults), axis=1)

演示:

In [78]: df['int_ip'] = ip_to_int(df.ip)

In [79]: df
Out[79]:
               ip      int_ip
0    61.245.160.1  1039507457
1  61.245.160.100  1039507556
2  61.245.160.200  1039507656
3  61.245.160.254  1039507710

检查:

In [80]: (df.ip.apply(lambda x: int(IPAddress(x))) == ip_to_int(df.ip)).all()
Out[80]: True
相关问题