将pandas DataFrame列附加到CSV

Bol*_*ain 6 python csv pandas

我正在尝试将pandas DataFrame(单列)附加到现有的CSV,就像这篇文章一样,但它不起作用!相反,我的列被添加到csv的底部,并反复重复(csv >>行的大小为列).这是我的代码:

with open(outputPath, "a") as resultsFile:
    print len(scores)
    scores.to_csv(resultsFile, header=False)
    print resultsFile
Run Code Online (Sandbox Code Playgroud)

终端输出:4032 <open file '/Users/alavin/nta/NAB/results/numenta/artificialWithAnomaly/numenta_art_load_balancer_spikes.csv', mode 'a' at 0x1088686f0>

先感谢您!

Anz*_*zel 7

就像@aus_lacy已经建议的那样,你只需要首先将csv文件读入数据帧,连接两个数据帧并将其写回csv文件:

假设你现有的数据框叫做df:

df_csv = pd.read_csv(outputPath, 'your settings here')

# provided that their lengths match
df_csv['to new column'] = df['from single column']

df_csv.to_csv(outputPath, 'again your settings here')
Run Code Online (Sandbox Code Playgroud)

而已.

  • 我试图避免打开和读取所有数据,但这确实有效:) (2认同)