Skip to main content
 首页 » 编程设计

python之带有两个数据帧的 Pandas append() 错误

2024年09月07日26lexus

当我尝试附加两个或更多数据帧并将结果输出到 csv 时,它显示为瀑布格式。

    dataset = pd.read_csv('testdata.csv') 
  for i in segment_dist: 
      for j in step: 
          print_msg = str(i) + ":" + str(j) 
          print("\n",i,":",j,"\n") 
          temp = pd.DataFrame(estimateRsq(dataset,j,i),columns=[print_msg]) 
          csv = csv.append(temp) 
  csv.to_csv('output.csv',encoding='utf-8', index=False) 

estimateRsq() 返回数组。我认为这么多代码片段应该足以帮助我。

我在 output.csv 中得到的格式是:

请帮忙,我怎样才能将内容从索引 1 移上去。

请您参考如下方法:

来自 df.append 文档:

Append rows of other to the end of this frame, returning a new object. Columns not in this frame are added as new columns.

如果要在右侧添加列,请使用 pd.concat 和 axis=1(水平方向):

list_of_dfs = [first_df, second_df, ...] 
pd.concat(list_of_dfs, axis=1) 

如果数据帧中的索引不匹配,您可能需要添加参数 ignore_index=True。