使用熊猫,我如何在没有标题的.csv文件中只读取列的子集(比如第4列和第7列)?我似乎不能用usecols来做这些。
当前回答
以前的答案是正确的,但在我看来,一个额外的names参数将使它完美,这应该是推荐的方式,特别是当csv没有头文件时。
解决方案
使用usecols和names参数
df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])
更多的阅读
或者使用header=None显式地告诉人们csv没有header(无论如何这两行是相同的)
df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)
这样你就可以通过
# with `names` parameter
df['colA']
df['colB']
而不是
# without `names` parameter
df[0]
df[1]
解释
基于read_csv,当显式传递名称时,header将表现为None而不是0,因此当存在名称时可以跳过header=None。
其他回答
确保指定pass header=None,并为第4列和第7列添加usecols=[3,6]。
为了读取一个没有标题的csv文件,并且只针对某些列,你需要为第4列和第7列传递params header=None和usecols=[3,6]:
df = pd.read_csv(file_path, header=None, usecols=[3,6])
查看文档
你也可以用header=None调用read_table()(读取文件的第一行作为数据的第一行):
df = pd.read_table('test.tsv', sep=',', usecols=[3,6], header=None)
如果分隔符是\t(,则此函数更有用。TSV文件等),因为默认分隔符是\t(不像read_csv的默认分隔符是,)。
As per documentation https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html : headerint, list of int, default ‘infer’ Row number(s) to use as the column names, and the start of the data. Default behavior is to infer the column names: if no names are passed the behavior is identical to header=0 and column names are inferred from the first line of the file, if column names are passed explicitly then the behavior is identical to header=None. Explicitly pass header=0 to be able to replace existing names. The header can be a list of integers that specify row locations for a multi-index on the columns e.g. [0,1,3]. Intervening rows that are not specified will be skipped (e.g. 2 in this example is skipped). Note that this parameter ignores commented lines and empty lines if skip_blank_lines=True, so header=0 denotes the first line of data rather than the first line of the file.
namesarray-like,可选 要使用的列名列表。如果文件包含标题行,则应该显式传递header=0以覆盖列名。此列表中的副本是不允许的。
columts = ['Day', 'PLMN', 'RNCname']
tempo = pd.read_csv("info.csv", sep=';', header=0, names=columts, index_col=False)
以前的答案是正确的,但在我看来,一个额外的names参数将使它完美,这应该是推荐的方式,特别是当csv没有头文件时。
解决方案
使用usecols和names参数
df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])
更多的阅读
或者使用header=None显式地告诉人们csv没有header(无论如何这两行是相同的)
df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)
这样你就可以通过
# with `names` parameter
df['colA']
df['colB']
而不是
# without `names` parameter
df[0]
df[1]
解释
基于read_csv,当显式传递名称时,header将表现为None而不是0,因此当存在名称时可以跳过header=None。
推荐文章
- 数据类vs类型。NamedTuple主要用例
- 如何从macOS完全卸载蟒蛇
- 是否有可能键入提示一个lambda函数?
- 'dict'对象没有has_key属性
- 使用Pandas groupby连接来自几行的字符串
- Pandas:给定列的数据帧行之和
- 如何避免在为Python项目构建Docker映像时重新安装包?
- 如何激活蟒蛇环境
- 省略[…]意思是在一个列表里?
- 将数据帧行按向量按特定顺序排序
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 在烧瓶中返回HTTP状态代码201
- 如何使用mongoimport导入CSV文件?