【问题标题】:TypeError: 'float' object is not iterable with apply lambdaTypeError: 'float' 对象不能用 apply lambda 迭代
【发布时间】:2019-05-17 13:26:14
【问题描述】:

我正在尝试将条件应用于我的 pandas 数据框中的列,但出现此错误:

TypeError: 'float' object is not iterable

Cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4'],
        'Price': [22.000,25.000,27.000,35.000]
        }

Cars = DataFrame(Cars, columns= ['Brand', 'Price'])
Cars ['Price'] = Cars ['Price'].apply(lambda x: [0 if y <= 25.000 else 1 for y in x])

有什么想法吗?

【问题讨论】:

  • 对于apply,函数的参数是容器的单个元素。换句话说,你只需要lambda x: 0 if x &lt;= 25.000 else 1,而不是lambda x: [0 if y &lt;= 25.000 else 1 for y in x]

标签: python pandas dataframe


【解决方案1】:

这里apply 是不好的选择,因为引擎盖下有循环,所以在大数据中速度很慢。更好的是使用带有numpy.where 的矢量化解决方案:

Cars ['Price'] = np.where(Cars ['Price'] <= 25.000, 0, 1)

或将innvert 条件转换为&gt; 并将integer 转换为True/False0/1 的映射:

Cars ['Price'] = (Cars ['Price'] > 25.000).astype(int)

print (Cars)

            Brand  Price
0     Honda Civic      0
1  Toyota Corolla      0
2      Ford Focus      1
3         Audi A4      1

【讨论】:

    【解决方案2】:

    不要遍历列表,.apply applies the function 到列中的每个元素!

    试试这条线:

    Cars ['Price'] = Cars ['Price'].apply(lambda x: 0 if x &lt;= 25.000 else 1)

    【讨论】:

    • 我的错我解释错了.apply的定义
    猜你喜欢
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 2015-10-23
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多