使用Python在循环中向数据帧添加新行

时间:2013-09-21 12:40:18

标签: 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 = concat(df1, DataFrame([{'col1': str1, 'col2': val1}]))

上面的代码不起作用,因为我一直收到错误:

  

UnboundLocalError:分配前引用的局部变量'df1'

我可以知道这样做的正确方法是什么?

0 个答案:

没有答案