Home > Blockchain >  DataFrame not filling with value generate from Loop in Python
DataFrame not filling with value generate from Loop in Python

Time:07-08

I am running a for loop in order to create a dataframe of 'New' values.

New = 0
Approved = 0
df = pd.DataFrame()
for row, rowdata in enumerate(combined):
    for col, value in enumerate(rowdata.values()):
        if col == 0:
            print(value)
        if col == 2:
            New  = value
            print('Original New')
            print(value)
        if col == 4:
            Approved = value
            if Approved > 0:
                New = New - Approved
            print('Updated New')
            print(New)
        df['New'] = New

Everything in this code seems to be working except for the last df['New'] = New statement. Any ideas on why that might be happening would be greatly appreciate.

CodePudding user response:

df['New'] = New is a wrong way to insert a single row.

One way to fix it:

all_rows = []
New = 0
Approved = 0
for row, rowdata in enumerate(combined):
    for col, value in enumerate(rowdata.values()):
        if col == 0:
            print(value)
        if col == 2:
            New  = value
            print('Original New')
            print(value)
        if col == 4:
            Approved = value
            if Approved > 0:
                New = New - Approved
            print('Updated New')
            print(New)
        # Accumulate all the rows
        all_rows.append(New)
# Finally create a dataframe 
df = pd.DataFrame({'New': all_rows})

  • Related