Working with Pandas dataframe and IPinfo’s API

Abdullah
Thu, 20 Apr 2023 18:51:58 +0000
Official Libraries

If you want to use Pandas to do analysis on IP Geolocation, we suggest, using IPinfo’s
Python module with the bulk/batch lookup method, getBatchDetails, even if you have a single IP address.

The reason for that is the getBatchDetails returns a dictionary of dictionary with the IP Address as the key, and the geolocation information as the value. This makes it fairly easy to convert to a Pandas dataframe and the column name gets assigned to the IP address.

For example:

# install with `pip install ipinfo`
import ipinfo
import pandas as pd

# initialize handler with access token
access_token = "insert_your_token_here"
handler = ipinfo.getHandler(access_token)

# declare the ip address list
# randomly generated IP addresses
ip_addresses = ['169.7.127.160', '90.130.144.160', '77.45.221.129', '27.167.41.249']

# do the IP address batch lookup
ip_data = handler.getBatchDetails(ip_addresses)

# convert it to a dataframe
df = pd.DataFrame(ip_data) # the default column names are the IP Addresses

# transposing the dataframe
df_trasposed = df.T # the IP Addresses will be the index column

When you lookup an IP address with getBatchDetails it returns the response like so -

{'18.236.88.186': {'ip': '18.236.88.186',
  'hostname': 'ec2-18-236-88-186.us-west-2.compute.amazonaws.com',
  'city': 'Boardman',
  'region': 'Oregon',
  'country': 'US',
  'loc': '45.8399,-119.7006',
  'org': 'AS16509 Amazon.com, Inc.',
  'postal': '97818',
  'timezone': 'America/Los_Angeles',
  'country_name': 'United States',
  'latitude': '45.8399',
  'longitude': '-119.7006'}}

Passing the getBatchDetails to Pandas.DataFrame and transposing the dataframe will generate a dataframe like this:

| ip | hostname | city | region | country | loc | org | postal | timezone | country_name | latitude | longitude
64.19.55.14 | 64.19.55.14 | http://64.19.55.14.nw.nuvox.net/ | Little Rock | Arkansas | US | 34.7871,-92.4222 | AS7029 Windstream Communications LLC | 72212 | America/Chicago | United States | 34.7871 | -92.4222
42.41.253.238 | 42.41.253.238 | nan | Seoul | Seoul | KR | 37.5660,126.9784 | AS9644 SK Telecom | 03141 | Asia/Seoul | South Korea | 37.566 | 126.978
44.141.143.69 | 44.141.143.69 | nan | San Diego | California | US | 32.7157,-117.1647 | AS16175 Signal Bredband AS | 92101 | America/Los_Angeles | United States | 32.7157 | -117.165
18.236.88.186 | 18.236.88.186 | http://ec2-18-236-88-186.us-west-2.compute.amazonaws.com/ | Boardman | Oregon | US | 45.8399,-119.7006 | AS16509 http://amazon.com/, Inc. | 97818 | America/Los_Angeles | United States | 45.8399 | -119.701
5.186.177.43 | 5.186.177.43 | nan | Taastrup | Capital Region | DK | 55.6501,12.3016 | AS44869 FIBIA P/S | 2630 | Europe/Copenhagen | Denmark | 55.6501 | 12.3016