You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中'Series'对象无'iterrows'属性的错误修正咨询

Python中'Series'对象无'iterrows'属性的错误修正咨询

嗨,我来帮你排查这个问题~

你遇到的AttributeError: 'Series' object has no attribute 'iterrows'错误,原因很明确:当你用a.loc['D1',]提取数据时,得到的是一个Series对象(DataFrame的单行数据默认返回Series),而iterrows()是专属DataFrame的遍历方法,Series根本没有这个属性,自然会报错。

下面给你几种可行的修正方案,你可以根据需求选择:

方案一:直接遍历Series的键值对(最简洁)

Series自带items()方法,可以直接遍历它的列名(键)和对应值,完全满足你的需求:

import pandas as pd

a = pd.DataFrame(index=['D1','D2','D3','D4'], columns=[x for x in range(0,10)])
a.loc[:] = 5

# 遍历D1行的每个列与对应值
for col, value in a.loc['D1',].items():
    if value > 0:
        print(True)

方案二:将单行转为DataFrame再使用iterrows()

如果你特别想用iterrows(),可以把提取的单行数据转成一个只有一行的DataFrame,这样就能正常调用方法了:

import pandas as pd

a = pd.DataFrame(index=['D1','D2','D3','D4'], columns=[x for x in range(0,10)])
a.loc[:] = 5

# 用双层方括号提取,得到单行DataFrame
row_df = a.loc[['D1'], :]
for index, row in row_df.iterrows():
    for col in a.columns:
        if row[col] > 0:
            print(True)

方案三:更高效的布尔索引方式

如果你的核心需求是检查该行元素是否大于0并打印True,还可以用Pandas的布尔索引直接筛选,代码更简洁高效:

import pandas as pd

a = pd.DataFrame(index=['D1','D2','D3','D4'], columns=[x for x in range(0,10)])
a.loc[:] = 5

# 筛选出D1行中大于0的元素,遍历打印True
for _ in a.loc['D1',][a.loc['D1',] > 0]:
    print(True)

备注:内容来源于stack exchange,提问作者Kang Dong Ho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.22 14:19:52