简体   繁体   English

DataFrame 未填充从 Python 中的 Loop 生成的值

[英]DataFrame not filling with value generate from Loop in Python

I am running a for loop in order to create a dataframe of 'New' values.我正在运行一个 for 循环以创建一个“新”值的数据框。

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.除了最后一个df['New'] = New语句之外,此代码中的所有内容似乎都在工作。 Any ideas on why that might be happening would be greatly appreciate.关于为什么会发生这种情况的任何想法将不胜感激。

df['New'] = New is a wrong way to insert a single row. df['New'] = New是插入单行的错误方法。

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})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM