2015-09-07 1992 views
1

是否有某种方法只使用Pandas(最好是read_csv)从csv文件中读取具有特定索引的特定列?我明白,read_csv提供了按列名读取特定列的功能,但数据文件没有标题,所以我不能使用列名。请注意,该文件太大,所以我不想读入整个文件,然后再读取子集。谢谢。如何使用pandas从csv读取特定的列索引

+1

'use_cols'支持基于序号的索引:'use_cols = [1,4]'将只读第二和第五列 – EdChum

+0

非常感谢。有用。 –

回答

3

下面是一个说明EdChum给出答案的例子。加载CSV文件有很多其他选项,请检查API reference

raw_data = {'first_name': ['Steve', 'Guido', 'John'], 
     'last_name': ['Jobs', 'Van Rossum', "von Neumann"]} 
df = pd.DataFrame(raw_data) 
# Saving data without header 
df.to_csv(path_or_buf='test.csv', header=False) 
# Telling that there is no header and loading only the first name 
df = pd.read_csv(filepath_or_buffer='test.csv', header=None, usecols=[1], names=['first_name']) 
df 

    first_name 
0  Steve 
1  Guido 
2  John 
0
import pandas as pd 
data = pd.read_csv('file.csv', usecols=['column_name']) 

usecols参数包含列姓名(或名称)的列表。如果想要多个列,然后用逗号分隔它们,即['column_name1, 'column_name2', 'column_name3']

相关问题