繁体   English   中英

将函数应用于DataFrame列将返回NoneType

[英]Applying a function to a DataFrame column returns NoneType

我有一个带有源IP地址的DataFrame,我想检查它们是否属于记录的CIDR范围。

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

我将所有已知的CIDR记录在字典中:

# 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”对象没有属性“ head”

我印象中此函数会将netmap()的返回值映射到DataFrame列。 这就是为什么我也要返回NAN的原因。 事实并非如此。 而且它超级慢。

问题是我在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对象,但是我想一切都有错误。

暂无
暂无

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

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