【问题标题】:Python lambda: TypeError: argument of type 'float' is not iterablePython lambda:TypeError:'float'类型的参数不可迭代
【发布时间】:2019-01-30 00:57:23
【问题描述】:

我试图从df['matrix'] 中提取信息到四个新列中。 df['matrix'] 看起来像这样:

  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'}

我的代码:

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)

我收到以下错误:

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

【问题讨论】:

  • 似乎x 是一个浮点数,而不是一个可迭代的(因此in x)失败了。 xdf['matrix'] 的一个元素,所以猜测一个是不同的类型。
  • 您确定'matrix' 列中的元素不再是字典吗?
  • 我无法用上面给出的数据重现您的问题。考虑到前面的评论,您可能已经更改了两者之间的数据,导致它不再是一个字典。试试看,例如df['matrix'].apply(lambda x: x.keys()) 工作。
  • "status" not in x.keys() 是否解决了错误?
  • 在您的数据中,所有行中都有'status'。所以只检查键中的状态是行不通的

标签: python pandas lambda


【解决方案1】:

由于您正在检查“状态”是否在 x 中,并且看起来有时 x 不是字符串。您可以使用 str(x) 将 x 转换为字符串。

希望它能解决你的问题。

【讨论】:

    猜你喜欢
    • 2022-11-08
    • 2020-05-07
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 2020-04-18
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多