Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I am using Pandas to sort a data frame. A handful of the columns are IP addresses that need to be sorted.

Is there a way to sort by IP addresses with Pandas easily? Is it possible to create a custom function I can use with Pandas to sort IP addresses?

I was able to sort a list of IP addresses, however I am having difficulty figuring out how to create custom sort functions with Pandas. Is there a way to incorporate inet_aton from the socket module?

I was able to accomplish this task on a list outside of Pandas:

list_of_ips = ['192.168.204.111', '10.10.10.10', '172.16.32.6', '1.1.1.1', '8.8.8.100']

sorted(list_of_ips, key=lambda ip: struct.unpack("!L", inet_aton(ip))[0])

['1.1.1.1', '8.8.8.100', '10.10.10.10', '172.16.32.6', '192.168.204.111']

I expect a column of IP-addresses in a data frame to be sorted with Pandas.

1 Answer

0 votes
by (25.1k points)

You can use pandas argsort method. Like this:

df.iloc[np.argsort(list(map(socket.inet_aton,list_of_ips)))]

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...