使用Python在循环中向dataframe添加新行
我希望在for循环中不断向数据帧添加行。 我目前的代码是:使用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
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