I am using python 3. I use database to lookup the country of IP, if the IP is not in the database, return None or AAA. After all process, show the return result (either a country name or None or AAA ) in a new column on the data frame, Specifically, I have three columns that are date time and IP in the data frame, I would like to add a new column "code1" that shows the country name or None of this IP.
I add error exception in the code, however, it doesn't work. The code and error message are as below. Can anyone help?
The following is the report when I add "from geoip2.errors import AddressNotFoundError" to my code. I guess it means when there is address not found in the database, it return nothing rather a "none" (see, there is a empty square brackets), therefore, when I use df['code1']=code1, it reports the number of value is not equal to the number of index. (I am not sure).
In fact,my aim is to add a column to my original data frame that report the country of each ip or none if it is not in the database. Is there any other way to do so instead of " df['code1']=code1 "? Any help will be appreciated. Thanks
Exceptions are just like any other object in Python. They have to be defined somewhere. In this case, AddressNotFoundError
is not defined so the interpreter has no idea what it means.
It has to be imported:
from geoip2.errors import AddressNotFoundError
or
import geoip2.errors.AddressNotFoundError
See relevant part of geoip2 documentation .
You can just leave out the AddressNotFoundError and instead do
try:
response1 = reader.country(row1)
code1.append(response1.country.iso_code)
except:
response1 = None
but if you really want to just except the AddressNotFoundError then at the top do
import geoip.errors.AddressNotFoundError
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.