1

I'm trying to use a for loop to iterate over an array and add items (new rows) to the dataframe. But when I I print out the DataFrame it's empty. I must be doing something wrong.

Here's my code:

sdf = pd.DataFrame(columns=('Question', 'Answer', 'Total', 'Percent'))
for i, data in enumerate(q_array):
    sdf.append({'Question': data.get_question(), 'Total': data.get_total()}, ignore_index=True)
    for answer, number in data.get_answers().items():
        sdf.append({'Answer': answer, 'Total': number, 'Percent': number_to_percent(number, data.get_total())}, ignore_index=True)
sdf.to_excel(writer, 'stats', index=False)
print(sdf)

Any suggestions on simply adding a new row, then adding data to the appropriate column?

1
  • 1
    Take a look at pd.concat Commented Jul 31, 2017 at 14:20

1 Answer 1

1

append is not an inplace operation. You need to assign the results of append back to the sdf variable.

sdf = pd.DataFrame(columns=('Question', 'Answer', 'Total', 'Percent'))
for i, data in enumerate(q_array):
    sdf = sdf.append({'Question': data.get_question(), 'Total': data.get_total()}, ignore_index=True)
    for answer, number in data.get_answers().items():
        sdf = sdf.append({'Answer': answer, 'Total': number, 'Percent': number_to_percent(number, data.get_total())}, ignore_index=True)
sdf.to_excel(writer, 'stats', index=False)
print(sdf)
Sign up to request clarification or add additional context in comments.

1 Comment

Coincidentally, as you were posting this answer, I tried that: sdf = sdf.append() and it seemed to give me the results I needed, haha. You're right, thank you very much for your explanation and solution.

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.