pandas 用熊猫替换csv文件python中的标题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35969916/
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
Replace header in a csv file python with pandas
提问by tafazzi87
I'm trying to replace header string of my csv
file with pandas libraries, but i can't understand how can I do this.
我正在尝试csv
用 Pandas 库替换我的文件的标题字符串,但我不明白我该怎么做。
I try to see DataFrame
but i don't see anything to do this.
anyone can help me?
thanks
我试着看看,DataFrame
但我看不出有什么可以做的。任何人都可以帮助我吗?谢谢
回答by Tom Barron
回答by tmthydvnprt
Reading csv
files in Pandas
csv
在 Pandas 中读取文件
There are many optionsavailable when reading csv
files. Here are some examples:
读取文件时有许多可用选项csv
。这里有些例子:
import pandas as pd
from cStringIO import StringIO
fake_csv_file = '''Col1,Col2,Col3
1,2,3
4,5,6
7,8,9'''
print 'Original CSV:'
print fake_csv_file
print
print 'Read in CSV File:'
df = pd.read_csv(StringIO(fake_csv_file))
print df
print
print 'Read in CSV File using multiple header lines:'
df = pd.read_csv(StringIO(fake_csv_file), header=[0,1])
print df
print
print 'Read in CSV File ignoring header rows:'
df = pd.read_csv(StringIO(fake_csv_file), skiprows=2)
print df
print
Original CSV:
Col1,Col2,Col3
1,2,3
4,5,6
7,8,9
Read in CSV File:
Col1 Col2 Col3
0 1 2 3
1 4 5 6
2 7 8 9
Read in CSV File using multiple header lines:
Col1 Col2 Col3
1 2 3
0 4 5 6
1 7 8 9
Read in CSV File ignoring header rows:
4 5 6
0 7 8 9
Writing csv
files in Pandas
csv
在 Pandas 中写入文件
There are many optionsavailable when writing css
files. Take careful note at the placement of commas in the final output in some the code below. Here are some examples:
写入文件时有许多可用选项css
。请仔细注意以下代码中最终输出中逗号的位置。这里有些例子:
# Set DataFrame back to original
df = pd.read_csv(StringIO(fake_csv_file))
print 'Write out a CSV file:'
print df.to_csv()
print
print 'Write out a CSV file with different headers:'
print df.to_csv(header=['COLA','COLB','COLC'])
print
print 'Write out a CSV without the pandas added index:'
print df.to_csv(index=False)
print
Write out a CSV file:
,Col1,Col2,Col3
0,1,2,3
1,4,5,6
2,7,8,9
Write out a CSV file with different headers:
,COLA,COLB,COLC
0,1,2,3
1,4,5,6
2,7,8,9
Write out a CSV without the pandas added index:
Col1,Col2,Col3
1,2,3
4,5,6
7,8,9
Notes:
笔记:
StringIO
and inline text is for example only. Normally, to read a specific file you'd usedf = pd.read_csv('/path/to/file.csv')
to_csv
without a file is used for example only. Normally, to write a specific file you'd usedf.to_csv('/path/to/file.csv')
StringIO
和内联文本仅作为示例。通常,要读取您使用的特定文件df = pd.read_csv('/path/to/file.csv')
to_csv
没有文件仅用作示例。通常,要编写您将使用的特定文件df.to_csv('/path/to/file.csv')