gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:01:54 25 4
gpt4 key购买 nike

将 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
<小时/>

我收到此错误:

'Series' object has no attribute 'split'

出了什么问题?

最佳答案

使用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

关于python - 使用 DataFrame 将 IP 地址转换为十进制时 split() 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45005596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com