IP2Location record to Pandas DataFrame

269 views Asked by At

I've used IP2Location to gather information on IP addresses and I want it in a DataFrame but when I tried to use pd.json_normalize(ip) I got an error. AttributeError: 'IP2LocationRecord' object has no attribute 'values'

The information I got from IP2Location is in this format,

{'ip': '66.249.79.244', 'country_short': 'US', 'country_long': 'United States of America', 'region': 'California', 'city': 'Mountain View', 'latitude': 37.405991, 'longitude': -122.078514, 'zipcode': '94043', 'timezone': '-08:00'}

I have also tried to use pd.DataFrame but the results in the df was empty, only the column names were seen.

df = pd.DataFrame(ip, columns = ['ip','country_short','country_long','region','city','latitude','longitude','zipcode','timezone'])

Expected outcome

     ip               country_short    country_long        ....       zipcode      timezone
0    66.249.69.244    US               United States of America       94043        -08:00
1

There are 1 answers

0
Proko On

Please pay attention to the error:

AttributeError: 'IP2LocationRecord' object ...

What you are trying to do, is to convert the object of type IP2LocationRecord to pandas.DataFrame which is not directly possible (you have to directly unpack all values, or create a dictionary out of fields of IP2LocationRecord). What you are seeing here :

{'ip': '66.249.79.244', 'country_short': 'US', 'country_long': 'United States of America', 'region': 'California', 'city': 'Mountain View', 'latitude': 37.405991, 'longitude': -122.078514, 'zipcode': '94043', 'timezone': '-08:00'}

is actually repr(ip) repr python3 reference (and not a dictionary)