0

I have the pandas df below, with a few columns, one of which is ip_addresses

    df.head()
           my_id   someother_id  created_at        ip_address     state
308074     309115   2859690   2014-09-26 22:55:20   67.000.000.000  rejected
308757     309798   2859690   2014-09-30 04:16:56   173.000.000.000  approved
309576     310619   2859690   2014-10-02 20:13:12   173.000.000.000  approved
310347     311390   2859690   2014-10-05 04:16:01   173.000.000.000 approved
311784     312827   2859690   2014-10-10 06:38:39   69.000.000.000  approved

For each ip_address I'm trying to return the description, city, country

I wrote a function below and tried to apply it

from ipwhois import IPWhois


def returnIP(ip) :
    obj = IPWhois(str(ip))
    result = obj.lookup_whois()

    description = result["nets"][len(result["nets"]) - 1 ]["description"]
    city = result["nets"][len(result["nets"]) - 1 ]["city"]
    country = result["nets"][len(result["nets"]) - 1 ]["country"]

    return [description, city, country]

# --- 

suspect['ipwhois'] = suspect['ip_address'].apply(returnIP)

My problem is that this returns a list, I want three separate columns.

Any help is greatly appreciated. I'm new to Pandas/Python so if there's a better way to write the function and use Pandas would be very helpful.

2 Answers 2

2
from ipwhois import IPWhois

def returnIP(ip) :
    obj = IPWhois(str(ip))
    result = obj.lookup_whois()

    description = result["nets"][len(result["nets"]) - 1 ]["description"]
    city = result["nets"][len(result["nets"]) - 1 ]["city"]
    country = result["nets"][len(result["nets"]) - 1 ]["country"]

    return (description, city, country)


suspect['description'], suspect['city'], suspect['country'] = \
suspect['ip_address'].apply(returnIP)
Sign up to request clarification or add additional context in comments.

4 Comments

I'm getting ValueError: too many values to unpack (expected 3)
Did you change the return value of the function to a tuple? (In you answer it was a list)
Yes, I did return (description, city, country) . I think it might be because some of the city values returned have commas in them.
What do you get if you do: suspect['ip_address'].apply(returnIP)[0]
0

I was able to solve it with another stackoverflow solution

for n,col in enumerate(cols):
    suspect[col] = suspect['ipwhois'].apply(lambda ipwhois: ipwhois[n])

If there's a more elegant way to solve this, please share!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.