0

I am trying to iterate through a dataframe, classify each row and add the output to the end of the row in a new column.

It seems to be adding the same classification to every row

dfMach = pd.read_csv("C:/Users/nicholas/Desktop/machineSum.csv", encoding='latin-1')
dfNew = dfMach
dfNew["Classification"] = ""

for index, row in dfMach.iterrows():
    aVar = dfMach['Summary'].iat[0]
    aClass = cl.classify(aVar)
    dfNew['Classification'] = aClass

Where am I going wrong?

Thank you

13
  • 1
    But wait a second. You are trying to fill all the data in new classification with the classify value returned from first value of summary ? Will that be of any use ? Commented Nov 13, 2017 at 11:39
  • 1
    But that ain't happening in your loop Commented Nov 13, 2017 at 11:41
  • 1
    May be you meant row['Summary'] instead of dfMach['Summary']. Its better you go for apply Commented Nov 13, 2017 at 11:44
  • 1
    Why use index when you can directly access row['Summary'] ? Commented Nov 13, 2017 at 11:47
  • 1
    Oh ok! so I can remove the .iat part and just have row['Summary], thank you! Commented Nov 13, 2017 at 11:48

1 Answer 1

5

Use apply instead of looping explicitly i.e

 dfMach['Classification'] = dfMach['Summary'].apply(cl.classify)

A couple of simple mistake to be corrected in your code and a bit of improvement i.e

dfNew = dfMach.copy() # dfNew = dfMach This will not let you create a new copy so you have to use dfMach.copy()

dfNew["Classification"] = ""

for index, row in dfMach.iterrows(): 
    # As @jez suggested we need to use loc for assignemnt 
    dfNew.loc[index, 'Classification'] = cl.classify(row['Summary'])
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, I will give it a go! :)
I understand what you mean now. Thank you!
@ScoutEU there are bit of things you need to take care of so check out the updated answer : )
Bharath, thank you for taking the time to clean up my code and for your help in this. Both you and Jezrael have been great and are reasons why I love the community on this website so much, there are no comparisons!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.