防止 pandas read_csv 将第一行视为列名的标题 [英] Prevent pandas read_csv treating first row as header of column names

查看:94
本文介绍了防止 pandas read_csv 将第一行视为列名的标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 pd.read_csv 读取 pandas DataFrame.我想将第一行保留为数据,但它不断转换为列名.

  • 我试过 header=False 但这只是完全删除了它.

(注意我的输入数据:我有一个字符串 (st = ' '.join(lst)),我将其转换为类似文件的对象(io.StringIO(st)),然后从该文件对象构建 csv.)

解决方案

你想要 header=NoneFalse 类型提升为 int进入 0 看到 文档强调我的:

<块引用>

header : int 或 int 列表,默认推断"行号用作列名和数据的开头.默认行为就像如果没有传递名称,则设置为 0,否则.显式传递 header=0能够替换现有名称.标题可以是一个列表为列上的多索引指定行位置的整数例如[0,1,3].未指定的中间行将被跳过(例如,本例中的 2 被跳过).注意这个参数忽略如果skip_blank_lines=True,则注释行和空行,所以header=0表示数据的第一行而不是文件的第一行.

你可以看到行为的不同,首先是header=0:

在 [95] 中:导入 io将熊猫导入为 pdt="""a,b,c0,1,23,4,5"""pd.read_csv(io.StringIO(t), header=0)出[95]:a b c0 0 1 21 3 4 5

现在使用 None:

在[96]中:pd.read_csv(io.StringIO(t), header=None)出[96]:0 1 20 a b c1 0 1 22 3 4 5

请注意,在最新版本 0.19.1 中,这将引发 TypeError:

在 [98] 中:pd.read_csv(io.StringIO(t), header=False)

<块引用>

TypeError: 将 bool 传递给 header 是无效的.使用 header=None 表示没有header 或 header=int 或类似整数的列表来指定行列名

I'm reading in a pandas DataFrame using pd.read_csv. I want to keep the first row as data, however it keeps getting converted to column names.

  • I tried header=False but this just deleted it entirely.

(Note on my input data: I have a string (st = ' '.join(lst)) that I convert to a file-like object (io.StringIO(st)), then build the csv from that file object.)

解决方案

You want header=None the False gets type promoted to int into 0 see the docs emphasis mine:

header : int or list of ints, default ‘infer’ Row number(s) to use as the column names, and the start of the data. Default behavior is as if set to 0 if no names passed, otherwise 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.

You can see the difference in behaviour, first with header=0:

In [95]:
import io
import pandas as pd
t="""a,b,c
0,1,2
3,4,5"""
pd.read_csv(io.StringIO(t), header=0)

Out[95]:
   a  b  c
0  0  1  2
1  3  4  5

Now with None:

In [96]:
pd.read_csv(io.StringIO(t), header=None)

Out[96]:
   0  1  2
0  a  b  c
1  0  1  2
2  3  4  5

Note that in latest version 0.19.1, this will now raise a TypeError:

In [98]:
pd.read_csv(io.StringIO(t), header=False)

TypeError: Passing a bool to header is invalid. Use header=None for no header or header=int or list-like of ints to specify the row(s) making up the column names

这篇关于防止 pandas read_csv 将第一行视为列名的标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆