将新行附加到 pandas 数据框会产生意想不到的结果

问题描述 投票:0回答:1

抱歉,如果这是一个愚蠢的问题,但我找不到解决方案。

我正在运行模型计算,并将关键输出变量放入列表中,以附加到结果主记录中。每次运行模型时都应添加一个新行。问题是添加一行后会创建一个新的索引列,将旧数据逐渐向右移动。我已经尝试了一切来抑制这个问题,但显然遗漏了一些东西 - 它应该如此简单!

model_output 是要附加为 df.new_row 的新变量列表

df_old 是驻留在云服务器上的要追加和重新保存的存档文件。

here is the resulting file showing the extra columns that appear each time a new line is added

here is what I want

这是代码 - 我尝试过 set_index、reset_index 等

如何每次抑制新的索引列?非常感谢,戴夫

# append results to model output

    model_output = [[date_today, bh_level_today, bh_change_today, PminusET_today, model, movement, proj_date_end,proj_depth_end]]
                    
    df_newrow = pd.DataFrame(model_output, columns=['date', 'height', 'rate', 'P_ET', 'model', 'statement', 'model_date','model_height'])
                    
  
# read model_output archive file and append new line
    df_old = pd.read_csv("ftp://............../wwwhome/FEM_model_output/model_output.csv")
    df_old.set_index('date')

    df_new = pd.concat([df_old, df_newrow], ignore_index=True, axis=0)
    df_new.set_index('date')
    df_new.reset_index(inplace=True, drop=True)

 # resave file
    buffer = io.StringIO()
    df_new.to_csv(buffer)
    text = buffer.getvalue()
    bio = io.BytesIO(str.encode(text))

    ftp.storbinary('STOR %s' % os.path.basename("model_output.csv"), bio)

    print('data uploaded')

    ftp.quit()
pandas concatenation
1个回答
0
投票

默认情况下,

pd.DataFrame.to_csv
将索引保存为 csv 文件中的列。 尝试:

df_new.to_csv(buffer, index=False)

或者,阅读时:

df_old = pd.read_csv("ftp://............../wwwhome/FEM_model_output/model_output.csv", index_col=0)

前者可能更好,因为您根据日期等设置自己的索引。但替代方案可能适用于最终遇到此问题的其他人。

© www.soinside.com 2019 - 2024. All rights reserved.