Search code examples
pythonpandasip-address

Is there a way to sort ip-addresses in a dictionary?


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.


Solution

  • In pandas we have argsort

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