Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

pandas中,新增一列,如何更好的实现数值型ip到字符型ip的转换

请问,在pandas中,还有没有更好用的方法,来新增一列,实现数值型ip向字符型ip的转换
以下是我现在使用的方法,效率好低。

import pandas as pd

def num2ip(num):
   return '%s.%s.%s.%s' % (
      (num & 0xff000000) >> 24, (num & 0x00ff0000) >> 16, (num & 0x0000ff00) >> 8, (num & 0x000000ff)
      )
# 整型ip和掩码
df = pd.DataFrame(
    {
        'ip_int': [1743822008, 1743822009, 2405182367, 2405182368],
        'mask': [32, 32, 32, 32]
    }
)
# 新增列,ip_f
IP = df.ip_int.values
ip_f = []
for ip in IP:
    ip_f.append(num2ip(ip))
seri_ip = pd.Series(ip_f)
df.loc[:,"ip_f"] = seri_ip
print(df)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

pandas 里有可以接受函数的方法 apply 不需要自己写循环

# 新增列,ip_f
df['ip_f'] = df.ip_int.apply(num2ip)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...