Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python在循环中向dataframe添加新行_Python_Loops_Dataframe_Add_Rows - Fatal编程技术网

使用Python在循环中向dataframe添加新行

使用Python在循环中向dataframe添加新行,python,loops,dataframe,add,rows,Python,Loops,Dataframe,Add,Rows,我希望在for循环中不断向数据帧添加行。 我目前的代码是: df1 = DataFrame() #empty df for i, row in df2.iterrows(): str1 = ... ... #obtain the str1 via some string manipulation with row val1 = ... ... #obtain the val1 via some numerical calculation with row df1 = c

我希望在for循环中不断向数据帧添加行。 我目前的代码是:

df1 = DataFrame()  #empty df
for i, row in df2.iterrows():
    str1 = ... ... #obtain the str1 via some string manipulation with row
    val1 = ... ... #obtain the val1 via some numerical calculation with row
    df1 = concat(df1, DataFrame([{'col1': str1, 'col2': val1}]))
上述代码不起作用,因为我不断收到错误:

UnboundLocalError:赋值前引用的局部变量“df1”


我可以知道正确的方法是什么吗?

该代码不会出现错误。你是对的,我已经简化了问题,但没有意识到它会影响错误。原始代码驻留在函数中,这就是错误的原因。我从函数中获取了它,现在它可以工作了(虽然我改为使用append而不是concat,因为它又出现了一个错误)。
谢谢Daniel