pandas DataFrame筛选price等于820000整行的方法咨询
报错原因
当前代码遍历对象写错了:autos.columns返回的是DataFrame的列名列表,每个元素都是字符串类型的列名,对字符串使用["price"]这种字符串键做索引,就会触发「字符串索引必须为整数」的报错,且代码中未定义index变量,即使遍历逻辑正确也无法正常输出。
实现方案
优先方案:pandas布尔索引(无需循环,效率最高)
不需要写for循环逐行判断,直接做条件筛选即可拿到所有price字段等于820000的整行数据:
# 筛选符合条件的所有行 target_rows = autos[autos["price"] == 820000] print(target_rows)
如果需要逐行拆分打印,可以搭配iterrows()遍历:
for row_index, row_data in target_rows.iterrows(): print(f"行索引:{row_index}") print(row_data)
iloc实现方式
iloc是按行的整数位置取值,需要先定位符合条件的行的整数位置,再逐行取出:
# 获取所有符合条件的行的整数位置 match_index = autos.index[autos["price"] == 820000].tolist() # 遍历位置用iloc取整行打印 for pos in match_index: print(autos.iloc[pos])
排查提示:如果运行后没有输出结果,先检查
price列的数据类型,如果列值带货币符号、千分位分隔符属于字符串类型,先做清洗转成数值类型再做等值判断,参考转换代码:autos["price"] = autos["price"].str.replace(r"[\$,]", "", regex=True).astype(int)
内容的提问来源于stack exchange,提问作者davidfunction
相关产品推荐
相关产品推荐

