将 Pandas DataFrame 列附加到 CSV
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27847258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append pandas DataFrame column to CSV
提问by BoltzmannBrain
I'm trying to append a pandas DataFrame (single column) to an existing CSV, much like this post, but it's not working! Instead my column is added at the bottom of the csv, and repeated over and over (rows in csv >> size of column). Here's my code:
我正在尝试将 Pandas DataFrame(单列)附加到现有的 CSV,就像这篇文章一样,但它不起作用!相反,我的列被添加到 csv 的底部,并一遍又一遍地重复(csv 中的行 >> 列的大小)。这是我的代码:
with open(outputPath, "a") as resultsFile:
print len(scores)
scores.to_csv(resultsFile, header=False)
print resultsFile
Terminal output:4032
<open file '/Users/alavin/nta/NAB/results/numenta/artificialWithAnomaly/numenta_art_load_balancer_spikes.csv', mode 'a' at 0x1088686f0>
终端输出:4032
<open file '/Users/alavin/nta/NAB/results/numenta/artificialWithAnomaly/numenta_art_load_balancer_spikes.csv', mode 'a' at 0x1088686f0>
Thank you in advance!
先感谢您!
回答by Anzel
Like what @aus_lacy has already suggested, you just need to read the csv file into a data frame first, concatenate two data frames and write it back to the csv file:
就像@aus_lacy 已经建议的那样,您只需要先将 csv 文件读入数据帧,连接两个数据帧并将其写回 csv 文件:
supposed your existing data frame called df:
假设您现有的数据框称为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')
That's it.
就是这样。

