使用DataFrame将IP地址转换为十进制时split()出错

时间:2017-07-10 07:00:50

标签: python pandas dataframe ip-address

将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

我收到了这个错误:

  

'系列'对象没有属性' split'

出了什么问题?

1 个答案:

答案 0 :(得分:1)

Dataframe使用str.split,然后按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]

如果需要返回string,请向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