Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

python - Pandas Writing Dataframe Columns to csv

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.

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.

Any help is appreciated, thanks!

question from:https://stackoverflow.com/questions/22019763/pandas-writing-dataframe-columns-to-csv

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...