I have a pandas dataframe of users and their ip addresses:
users_df = pd.DataFrame({'id': [1,2,3],
'ip': ['96.255.18.236','105.49.228.135','104.236.210.234']})
id ip
0 1 96.255.18.236
1 2 105.49.228.135
2 3 104.236.210.234
And a separate dataframe containing network ranges and corresponding geoname IDs:
geonames_df = pd.DataFrame({'network': ['96.255.18.0/24','105.49.224.0/19','104.236.128.0/17'],
'geoname': ['4360369.0','192950.0','5391959.0']})
geoname network
0 4360369.0 96.255.18.0/24
1 192950.0 105.49.224.0/19
2 5391959.0 104.236.128.0/17
For each user, I need to check their ip against all networks, and pull out the corresponding geoname and add it to users_df
. I want this as output:
id ip geonames
0 1 96.255.18.236 4360369.0
1 2 105.49.228.135 192950.0
2 3 104.236.210.234 5391959.0
In this example its easy because they're correctly ordered and only 3 examples. In reality, users_df
has 4000 rows, and geonames_df
has over 3 million
I'm currently using this:
import ipaddress
networks = []
for n in geonames_df['network']:
networks.append(ipaddress.ip_network(n))
geonames = []
for idx, row in users_df.iterrows():
ip_address = ipaddress.IPv4Address(row['ip'])
for block in networks:
if ip_address in block:
geonames.append(str(geonames_df.loc[geonames_df['network'] == str(block), 'geoname'].item()))
break
users_df['geonames'] = geonames
This is very slow because of the nested loop over the dataframe/list. Is there a faster way that leverages numpy/pandas? Or at least some way that is faster than the method above?
Theres a similar question about this (How can I check if an ip is in a network in python 2.x?), but 1) it doesnt involve pandas/numpy, 2) I want to check multiple IPs against multiple networks, and 3) the highest voted answer cant avoid a nested loop, which is where my slow performance stems from