2016-10-04 82 views
0

我有一个DataFrame与源IP地址,我想检查它们是否属于记录的CIDR范围。对DataFrame列应用函数返回NoneType

netflow_df2["sip"].head(10) 

timestamp 
2016-10-04 16:24:58 40.101.X.X 
2016-10-04 16:24:58 40.101.X.X 
2016-10-04 16:24:58  40.101.X.X 
2016-10-04 16:24:58  67.X.X.X 
2016-10-04 16:24:58  10.1.1.X 
2016-10-04 16:24:58  10.1.Y.Y 



import ipaddress 
import numpy 
from collections import defaultdict 
from pandas.util.testing import test_parallel 

我把所有的记录CIDRs我知道在一个字典:

# dict to key (vlan, designation) 
nets = defaultdict(str) 
nets["10.1.0.0/24"] = "13, web" 
net["10.2.0.0/24"] = "14, department X" 
net["10.3.55.0/24"] = "601, wifi" 
... 
net["10.1.243.0/24"] = "1337, IT" 

我定义我的功能:

def netmap(ip, network_lookup_dict): 
    for key, value in network_lookup_dict.iteritems() : 
     if ipaddress.ip_address(unicode(ip)) in ipaddress.ip_network(unicode(key)): 
      return value 
      # print "VLAN: " + infos[0].strip() + ", Network designation: " + infos[1].strip() 
     else: 
      return numpy.NAN 

现在我映射它:

@test_parallel(num_threads=4) 
def apply_netmap(netflow_df2, location="ABC"): 
    % time netflow_df2["sip_infos"] = netflow_df2["sip"].map(lambda ip: netmap(ip, nets)) 
    return netflow_df2 


CPU times: user 3min 14s, sys: 21.2 s, total: 3min 36s 
Wall time: 3min 5s 


netflow_df3 = apply_netmap(netflow_df2) 

我的错误是:

netflow_df3.head(10) 

AttributeError: 'NoneType' object has no attribute 'head'

我的印象是这个函数会的netmap()返回值映射到数据框栏下。这也是我返回NAN的原因。这似乎并非如此。它也超级慢。

+1

你的功能需要有'return netflow_df2' –

+0

对不起,复制粘贴错误。 – wishi

+1

这是什么:if ipaddress.ip_address(unicode(ip))in ipaddress.ip_network(unicode(key)) –

回答

0

问题是我在netmap函数中使用defaultdict错误。这产生了更正结果:

def netmap(ip, network_lookup_dict): 
    for key, value in network_lookup_dict.iteritems(): 
     try: 
      if ipaddress.ip_address(unicode(ip)) in ipaddress.ip_network(unicode(key)): 
       return network_lookup_dict.get(key) 
     except KeyError: 
      print "duh" 
      return numpy.NaN 

return声明已损坏。这让我感到困惑,为什么这会破坏DataFrame对象,但我认为一切都有错误。