Patthebug
Patthebug

Reputation: 4787

df.append() not adding rows to dataframe in pandas

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?

Upvotes: 0

Views: 303

Answers (1)

Parfait
Parfait

Reputation: 107642

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

Upvotes: 1

Related Questions