0

i want to find a country from city list

import pandas as pd
from geopy.geocoders import Nominatim

# read the Excel file
df = pd.read_excel('testcity.xlsx')

# initialize the geolocator
geolocator = Nominatim(user_agent='my-app')

# define a function to get the country from a city name
def get_country(city):
    location = geolocator.geocode(city, language='en')
    if location is not None:
        return location.raw['display_name']
        s.display_name
    else:
        return None

# apply the function to the city column and create a new column for the country
df['Country'] = df['City'].apply(get_country)
print(df.Country)
df.Country=df.Country.apply(lambda x : x.split(", ")[-1])

# read the Excel file
print(df.Country)
# save the updated Excel file
df.to_excel('test_city.xlsx', index=False)
1.Bellad Bagewadi, SH73, Bellada Bagewadi, Hukke...
2.Chandor, Salcete, South Goa, Goa, 403714, India
3.Police Training School, Hubli-Dharwad, Someshw

split function is not working giving me error:

Input In [24], in <lambda>(x)
     22 df1=df['Country']
     23 if df1.notnull:
---> 24     df.Country=df.Country.apply(lambda x : x.split(", ")[-1])
     26 # read the Excel file
     27 print(df.Country)

AttributeError: 'NoneType' object has no attribute 'split'
Michael Butscher
  • 10,028
  • 4
  • 24
  • 25
vishakhaa
  • 1
  • 1
  • Don't assign to an attribute: `df['Country'] = df['Country'].apply(lambda x : x.split(", ")[-1])`. Also, use `str.split`, not `apply` – mozway Mar 06 '23 at 10:42

0 Answers0