Python lambda: TypeError: argument of type 'fl

2019-08-21 05:09发布

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

1条回答
再贱就再见
2楼-- · 2019-08-21 05:47

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.

查看更多
登录 后发表回答