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
xis a float, not an iterable (and soin x) fails.xis an element ofdf['matrix']so guessing one is of a different type.'matrix'columns are dictionaries any more?df['matrix'].apply(lambda x: x.keys())works."status" not in x.keys()resolve the error?'status'in all the rows. So just checking status in keys is not going to work