1

When Converting IP address to decimal:

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

I got this error:

'Series' object has no attribute 'split'

What's wrong?

1 Answer 1

1

Use str.split for Dataframe and then convert all columns to int by astype. Last call function:

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]

If need return strings add casting to 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']

If data2 is DataFrame and need new column:

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
Sign up to request clarification or add additional context in comments.

1 Comment

Many Thanks~ It's very helpful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.