没有标题的Python csv
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3387191/
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
Python csv without header
提问by bobsr
With header information in csv file, city can be grabbed as:
使用 csv 文件中的标题信息,可以将城市抓取为:
city = row['city']
Now how to assume that csv file does not have headers, there is only 1 column, and column is city.
现在如何假设 csv 文件没有标题,只有 1 列,列是城市。
采纳答案by nosklo
You can still use your line, if you declare the headers yourself, since you know it:
如果您自己声明标题,您仍然可以使用您的行,因为您知道:
with open('data.csv') as f:
cf = csv.DictReader(f, fieldnames=['city'])
for row in cf:
print row['city']
For more information check csv.DictReaderinfo in the docs.
有关更多信息,请查看csv.DictReader文档中的信息。
Another option is to just use positional indexing, since you know there's only one column:
另一种选择是仅使用位置索引,因为您知道只有一列:
with open('data.csv') as f:
cf = csv.reader(f)
for row in cf:
print row[0]
回答by Robert Trent
I'm using a pandas dataframe object:
我正在使用熊猫数据框对象:
df=pd.read_sql(sql_query,data_connection)
df.to_csv(filename, header=False, index=False)
Don't know if that is the most Pythonic approach, but it gets the job done.
不知道这是否是最 Pythonic 的方法,但它完成了工作。
回答by Marat
You can use pandas.read_csv()function similarly to the way @nosklo describes, as follows:
您可以像@nosklo 描述的那样使用pandas.read_csv()函数,如下所示:
df = pandas.read_csv("A2", header=None)
print df[0]
or
或者
df = pandas.read_csv("A2", header=None, names=(['city']))
print df['city']

