0

I want to compare 2 dataframe rows to eachother. When I try to run my code I get this error: TypeError: string indices must be integers.

this is my code:

for item in df:
    if item["comment text"] != item["original text"]:
        counter1 += 1

thanks in advance.

Lars Assen
  • 55
  • 1
  • 7
  • item is a string not a dictionary. – tomgalpin Mar 02 '20 at 13:55
  • Does this answer your question? [How to iterate over rows in a DataFrame in Pandas?](https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas) – tomgalpin Mar 02 '20 at 13:58

2 Answers2

1

You need to use the iterrows() function to iterate through a Pandas DataFrame

for index,item in data.iterrows():
    if item["comment text"] != item["original text"]:
        counter1 += 1
Ahmed Mohamedeen
  • 328
  • 3
  • 11
  • _You need to use the iterrows() function to iterate through a Pandas DataFrame_ Not only do you not **need** to use `iterrows()`, you really shouldn't. – AMC Mar 02 '20 at 18:18
  • @AMC Do you mean itertuples would be better for his case? – Ahmed Mohamedeen Mar 02 '20 at 18:24
  • `itertuples()` is one option, yes, although I think it's important to mention that explicitly looping over a DataFrame is unidiomatic and rarely necessary. – AMC Mar 02 '20 at 18:25
-1

If df is a DataFrame, you iterate it wrongly (the right way is for i_row, row in df.iterrows():... On the other hand, it's unclear what exactly you want to compare with what. As for me, the problem isn't posed clearly.

Oleg O
  • 1,005
  • 6
  • 11