0

I was trying to extract information from df['matrix'] into four new columns. The df['matrix'] look like this:

  id       matrix
   0  {'status': 'ZERO_RESULTS'}
   1  {'distance': {'text': '3,899 km', 'value': 3898595}, 'duration': {'text': '1 day 13 hours', 'value': 133445}, 'status': 'OK'}
   2  {'distance': {'text': '2,065 km', 'value': 2065157}, 'duration': {'text': '20 hours 7 mins', 'value': 72393}, 'status': 'OK'}

my code:

df['dist_value'] = df['matrix'].apply(lambda x: round((x['distance']['value']) / 1000) if "status" not in x else None)
df['dist_text'] = df['matrix'].apply(lambda x: x['distance']['text'] if "status" not in x else None)

df['duration_value'] = df['matrix'].apply(lambda x: float("%.2f" %((x['duration']['value'])/60/60)) if "status" not in x else None)
df['duration_text'] = df['matrix'].apply(lambda x: x['duration']['text'] if "status" not in x else None)

I get the following error:

df['dist_value'] = df['matrix'].apply(lambda x: round((x['distance']['value']) / 1000) if "status" not in x else None)
TypeError: argument of type 'float' is not iterable
7
  • 1
    Seems like x is a float, not an iterable (and so in x) fails. x is an element of df['matrix'] so guessing one is of a different type. Commented Aug 23, 2018 at 15:32
  • 1
    Are you sure your elements inside the 'matrix' columns are dictionaries any more? Commented Aug 23, 2018 at 15:33
  • 2
    I can't reproduce your problem with the data given as above. With the previous comment in mind, you have probably altered the data in between, causing it not to be a dict anymore. Try and see if e.g. df['matrix'].apply(lambda x: x.keys()) works. Commented Aug 23, 2018 at 15:37
  • 1
    does "status" not in x.keys() resolve the error? Commented Aug 23, 2018 at 16:08
  • 1
    In your data, you have 'status' in all the rows. So just checking status in keys is not going to work Commented Aug 24, 2018 at 5:41

1 Answer 1

3

Since you are checking if "status" is in x and it looks like sometimes x is not a string. You can cast your x to string with str(x).

Hope it will solve your problem.

Sign up to request clarification or add additional context in comments.

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.