Welcome to OGeek Q&A 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 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...