如何在 pandas 中将所有IP地址列表转换为十进制数字 [英] How to convert all IP address lists to decimal numbers in Pandas
本文介绍了如何在 pandas 中将所有IP地址列表转换为十进制数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有大量的列表数据,如何将所有IP地址转换为熊猫中的十进制数字并与第二列的值合并
There is huge list data, how to convert all IP addresses to decimal numbers in pandas and merge with the value of the second column
import pandas as pd
filename = "/Users/sda/Desktop/file"
pdd = pd.read_csv(filename,header=None,sep='|',error_bad_lines=False, warn_bad_lines=False,skiprows=[0],
names=['Name','Code','Ipv', 'Ip','Range','Date', 'Category'])
pd.options.display.max_columns = None
k = pdd[pdd['Ipv'].str.contains("ipv4") & pdd['Ip'].str.contains('[0-9]')]
print(k[['Ip','Range','Code']])
我的输出:
Ip Range Code
2.16.0.0 524288 EU
200.109.100.0 1024 RU
200.109.102.0 1024 RU
只需要获取具有相同国家代码和范围号的第一个IP地址的十进制值即可,仅与第二列的值合并
only need to get the decimal value of the first IP address with the same country code and range number.merge with the value of the second column only
IP range code
3362612224 2028 RU
推荐答案
IIUC,考虑到输出的数据框名称为df
,如下所示:
IIUC, Considering the dataframe name of the output is df
, something like this:
import socket, struct
def ip2int(ip):
"""
Convert an IP string to int
"""
packedIP = socket.inet_aton(ip)
return struct.unpack("!L", packedIP)[0]
df['ip_int'] = df.Ip.apply(ip2int)
df['range_sum']=df.groupby(['Code'])['Range'].transform('sum')
df[df.Code.duplicated(keep='last')]
Ip Range Code ip_int range_sum
1 200.109.100.0 1024 RU 3362612224 2048
这篇关于如何在 pandas 中将所有IP地址列表转换为十进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文