0

I'm using a very simple piece of code and initializing a pandas dataframe with a single row and then adding other rows from a list named itemsets_dct and then appending them to the dataframe, using the following code:

finalResults = pd.DataFrame({'Concept1': itemsets_dct[0][0][0], 'Concept2': itemsets_dct[0][0][1], 'Concept3': itemsets_dct[0][0][2], 'Concept4': itemsets_dct[0][0][3], 'Count': itemsets_dct[0][1]}, index=[0])
for i in range(1,len(itemsets_dct)):
    tempResult = pd.DataFrame({'Concept1': itemsets_dct[i][0][0], 'Concept2': itemsets_dct[i][0][1], 'Concept3': itemsets_dct[i][0][2], 'Concept4': itemsets_dct[i][0][3], 'Count': itemsets_dct[i][1]}, index=[i])
    finalResults.append(tempResult)

when I run this code, it executes without any errors, but the finalResults variable only has 1 row, the row that I initialized.

Why is the code not appending rows to the dataframe?

3
  • 8
    append is not an inplace operation, so you need to reassign. i.e. finalResults = finalResults.append(tempResult). Commented Nov 1, 2016 at 18:15
  • Can't imagine the sdolution would be so simple. Thanks a lot. Commented Nov 1, 2016 at 18:16
  • Also show the contents of itemsets_dct as there may be a preferred way to do this in one call instead of iteratively in loop. Commented Nov 1, 2016 at 21:05

1 Answer 1

1

Consider not using an iterative for loop append but building a list of dictionaries that you then cast into a dataframe all in one call. Below hopefully recreates the outer structure of your nested list:

itemsets_dct = [[['check1', 'check2', 'check3', 'check4'], 3],
                [['check11', 'check22', 'check33', 'check44'], 3],
                [['check111', 'check222', 'check333', 'check444'], 3]]

dfDict = [{'Concept1': i[0][0],
           'Concept2': i[0][1],
           'Concept3': i[0][2],
           'Concept4': i[0][3],
           'Count': i[1]} for i in itemsets_dct]

finalresults = pd.DataFrame(dfDict)
print(finalresults)

#    Concept1  Concept2  Concept3  Concept4  Count
# 0    check1    check2    check3    check4      3
# 1   check11   check22   check33   check44      3
# 2  check111  check222  check333  check444      3
Sign up to request clarification or add additional context in comments.

Comments

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.