如何使用pandas从csv读取特定的列索引

2024-06-12 04:21:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 文件csv方法功能标题pandasread数据文件
2条回答
import pandas as pd
data = pd.read_csv('file.csv', usecols=['column_name'])

usecols的参数包含列名列表。如果需要多个列,则用逗号分隔它们,即['column_name1, 'column_name2', 'column_name3']

下面是一个例子,说明埃德楚姆给出的答案。有很多附加选项可以加载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

相关问题 更多 >