【问题标题】:Error with split() when converting IP address to decimal using DataFrame使用 DataFrame 将 IP 地址转换为十进制时 split() 出错
【发布时间】:2017-12-13 19:22:27
【问题描述】:

IP地址转十进制时:

def ip2Int(ip):
    o = map(int, ip.split('.'))
    res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
    return res

intIP=[]
for row in data2:
    intIP.append(ip2Int(data2[row].astype(str)))
    print intIP[row]

print intIP

我收到了这个错误:

“系列”对象没有属性“拆分”

怎么了?

【问题讨论】:

    标签: python pandas dataframe ip-address


    【解决方案1】:

    str.split 用于Dataframe,然后通过astype 将所有列转换为int。最后调用函数:

    data2 = pd.Series(['85.237.234.182','95.237.234.187','85.237.134.187','85.207.234.187'])
    print (data2)
    0    85.237.234.182
    1    95.237.234.187
    2    85.237.134.187
    3    85.207.234.187
    dtype: object
    
    def ip2Int(ip):
        o = ip.str.split('.', expand=True).astype(int)
        res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
        return res
    
    s = ip2Int(data2)
    print (s)
    0    1441655478
    1    1609427643
    2    1441629883
    3    1439689403
    dtype: int32
    
    intIP = ip2Int(data2).tolist()
    print (intIP)
    [1441655478, 1609427643, 1441629883, 1439689403]
    

    如果需要返回strings 添加转换到str:

    def ip2Int(ip):
        o = ip.str.split('.', expand=True).astype(int)
        res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
        return res.astype(str)
    
    s = ip2Int(data2)
    print (s)
    0    1441655478
    1    1609427643
    2    1441629883
    3    1439689403
    dtype: object
    
    intIP = ip2Int(data2).tolist()
    print (intIP)
    ['1441655478', '1609427643', '1441629883', '1439689403']
    

    如果data2DataFrame 并且需要新列:

    def ip2Int(ip):
        o = ip.str.split('.', expand=True).astype(int)
        res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
        return res
    
    data2['intIP'] = ip2Int(data2['col'])
    print (data2)
                  col       intIP
    0  85.237.234.182  1441655478
    1  95.237.234.187  1609427643
    2  85.237.134.187  1441629883
    3  85.207.234.187  1439689403
    

    【讨论】:

    • 非常感谢~很有帮助!
    • 很高兴能帮上忙。如果我的回答有帮助,请不要忘记 accept 它 - 单击答案旁边的复选标记 () 将其从灰色切换为已填充。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2013-11-13
    • 2016-07-05
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    相关资源
    最近更新 更多