1

I've been been trying the lat and long of dataframe using geocoder.

I managed to get the lat/long of distict city and save it into a file. However, I got an error when try to map the data to other data of city as Im not sure how to do so.

My code:

def func(a):
    if a in data2['CITY']:
        return data2['LATITUDE']
    else:
        return "0"

data["LATITUDE"] = data["CITY"].apply(lambda x: func(x))
6
  • 1
    "I got an error" - what's the error? Commented Jun 23, 2021 at 15:38
  • Sidenote: lambda x: func(x) is redundant. Just use func. This is called eta-reduction btw. Commented Jun 23, 2021 at 16:11
  • With data2 = pd.to_excel(r'/'), I get AttributeError: module 'pandas' has no attribute 'to_excel'. Maybe you meant pd.read_excel()? But then you'd get IsADirectoryError: [Errno 21] Is a directory: '/'. Please provide a minimal reproducible example. Commented Jun 23, 2021 at 16:17
  • yes correct. edited with sample dataset Commented Jun 23, 2021 at 16:24
  • Can you post the output of print(deduplokasi.head().to_dict() and print(data2.head().to_dict()? Commented Jun 23, 2021 at 16:24

2 Answers 2

1

If I understand correctly, you can generate data['LATITUDE'] by reindexing.

Set data2's index to CITY and reindex() against data's CITY:

data['LATITUDE'] = data2.set_index('CITY').reindex(data['CITY'])['LATITUDE'].values
Sign up to request clarification or add additional context in comments.

Comments

1

In pandas, if you check if a certain element is in a pd.Series, you need to first get it to an array form:

'SCOTLAND' in data2['CITY'] -> False
'SCOTLAND' in data2['CITY'].values -> True

After making this fix, you need to make it so that it returns a single element, not a vector. So, finally:

def func(a):
    if a in data2['CITY'].values:
        return data2.loc[data2['CITY'] == a, 'LATITUDE'].item()
    else:
        return "0"

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.