python - pandas read_csv index_col=None 不使用每行末尾的分隔符

标签 python pandas

我正在阅读“用于数据分析的 Python”一书,在“示例:2012 年联邦选举委员会数据库”部分将数据读取到 DataFrame 时遇到问题。问题是其中一列数据总是被设置为索引列,即使 index_col 参数设置为 None。

这里是数据的链接:http://www.fec.gov/disclosurep/PDownload.do .

这是加载代码(为了节省检查时间,我设置了nrows=10):

import pandas as pd
fec = pd.read_csv('P00000001-ALL.csv',nrows=10,index_col=None)

为了简短起见,我不包括数据列输出,但这是我的输出(请不要索引值):

In [20]: fec

Out[20]:
<class 'pandas.core.frame.DataFrame'>
Index: 10 entries, C00410118 to C00410118
Data columns:
...
dtypes: float64(4), int64(3), object(11)

这是本书的输出(同样不包括数据列):

In [13]: fec = read_csv('P00000001-ALL.csv')
In [14]: fec
Out[14]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1001731 entries, 0 to 1001730
...
dtypes: float64(1), int64(1), object(14)

我的输出中的索引值实际上是文件中的第一列数据,然后将所有其余数据向左移动一个。有谁知道如何防止这列数据被列为索引?我希望索引只是 +1 增加整数。

我对 python 和 pandas 还很陌生,因此对于给您带来的任何不便,我深表歉意。谢谢。

最佳答案

快速解答

使用 index_col=False而不是 index_col=None当您在每行末尾有分隔符以关闭索引列推断并丢弃最后一列时。

更多详情

查看数据后,每行末尾都有一个逗号。还有这句话(自创建此帖子以来,文档已被编辑):

index_col: column number, column name, or list of column numbers/names, to use as the index (row labels) of the resulting DataFrame. By default, it will number the rows without using any column, unless there is one more data column than there are headers, in which case the first column is taken as the index.

来自 the documentation表明 pandas 认为您有 n 个标题和 n+1 个数据列,并将第一列视为索引。


编辑 2014 年 10 月 20 日 - 更多信息

我找到了 another valuable entry这特别是关于尾随限制器以及如何简单地忽略它们:

If a file has one more column of data than the number of column names, the first column will be used as the DataFrame’s row names: ...

Ordinarily, you can achieve this behavior using the index_col option.

There are some exception cases when a file has been prepared with delimiters at the end of each data line, confusing the parser. To explicitly disable the index column inference and discard the last column, pass index_col=False: ...

关于python - pandas read_csv index_col=None 不使用每行末尾的分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12960574/

相关文章:

python - 有人对 telnetlib.expect() 有好感吗?

Python Tkinter : Remove window border

python - 查找 pandas 数据框中列的经度和纬度

python - 计算距图像中心的像素距离

pandas 按子组的平均值划分组

python - 将数据帧列转换为列表列表,然后转换回数据帧,同时保持 ID 关联

python - 在函数中迭代 Pandas 系列的行

python - 从 MS Word 中提取数据

python - 如何在 PyCharm 中重新初始化 Python 控制台?

python - 将实际文件添加到列表中,而不仅仅是文件的字符串名称