AttributeError: 'Series' object has no attribute 'iterrows'
Asked Answered
A

2

26
accounts = pd.read_csv('C:/*******/New_export.txt', sep=",", dtype={'number': object})
accounts.columns = ["Number", "F"]

for i, j in accounts["Number"].iterrows(): #i represents the row(index number), j is the number
    if (str(j) == "27*******5"):
        print(accounts["F"][i], accounts["Number"][i])

I get the following error:

AttributeError: 'Series' object has no attribute 'iterrows'

I don't quite understand the error since "accounts" is a pandas dataframe.

Amur answered 4/3, 2019 at 20:25 Comment(0)
P
39

accounts["Number"] is a Series object, not a DataFrame. Either iterate over accounts.iterrows() and take the Number column from each row, or use the Series.items() method.

Iterating over the dataframe:

for i, row in accounts.iterrows():
    if str(row['Number']) == "27*******5":
        print(row["F"], row["Number"])

or over Series.items():

for i, number in accounts['Number'].items():
    if str(number) == "27*******5":
        print(accounts["F"][i], number)
Parthen answered 4/3, 2019 at 20:28 Comment(0)
L
1

To iterate over a dataframe column (such as accounts['Number']) or a pandas Series, use items(), which creates a zip object.

for i, j in accounts["Number"].items():
#                             ^^^^^^^^^
    if (str(j) == "27*******5"):
        print(accounts["F"][i], accounts["Number"][i])

That said, iterating over a column is rarely needed as there are faster ways to filter a column. For example, for the case in the OP, filtering using a boolean mask instead of the if-clause produces the same thing:

print(accounts.loc[accounts["Number"].map(str) == "27*******5", ['F', 'Number']])
Lunalunacy answered 18/3, 2023 at 5:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.