Python Pandas 将数据框列写入 csv
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22019763/
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
Pandas Writing Dataframe Columns to csv
提问by Harrison Boles
I'm writing a script to reduce a large .xlsx file with headers into a csv, and then write a new csv file with only the required columns based on header name.
我正在编写一个脚本,将带有标题的大型 .xlsx 文件缩减为 csv,然后根据标题名称编写一个仅包含所需列的新 csv 文件。
import pandas
import csv
df = pandas.read_csv('C:\Python27\Work\spoofing.csv')
time = df["InviteTime (Oracle)"]
orignum = df["Orig Number"]
origip = df["Orig IP Address"]
destnum = df["Dest Number"]
df.to_csv('output.csv', header=[time,orignum,origip,destnum])
The error I'm getting is with that last bit of code, and it says
我得到的错误是最后一点代码,它说
ValueError: Writing 102 cols but got 4 aliases
I'm sure i'm overlooking something stupid, but I've read over the to_csv documentation on the pandas website and I'm still at a loss. I know I'm using the to_csv parameters incorrectly but I can't seem to get my head around the documentation I guess.
我确定我忽略了一些愚蠢的事情,但我已经阅读了 pandas 网站上的 to_csv 文档,但我仍然不知所措。我知道我错误地使用了 to_csv 参数,但我想我似乎无法理解文档。
Any help is appreciated, thanks!
任何帮助表示赞赏,谢谢!
采纳答案by user1827356
The way to select specific columns is this -
选择特定列的方法是这样的 -
header = ["InviteTime (Oracle)", "Orig Number", "Orig IP Address", "Dest Number"]
df.to_csv('output.csv', columns = header)

