简体   繁体   中英

Python lambda: TypeError: argument of type 'float' is not iterable

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

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM