这里有很多关于 pandas 在读/写 csv 文件时不遵守列顺序的问题,其中一些可以追溯到 5 年前 (!):
- Preserving column order in Python Pandas DataFrame
- Python Pandas read_csv Keep Column Order
- Keeping columns in the specified order when using UseCols in Pandas Read_CSV
根据 this answer ,此“错误”已在 0.19.0 版中修复,但我正在运行 Python 3.6.4 和 pandas 0.22.0,但我仍然遇到此问题。
这是一个已经存在多年的错误,还是 pandas 的工作原理?如果是这样,不保留列顺序的原因是什么?
您可以使用 this csv file 重现问题和以下代码:
import pandas as pd
df = pd.read_csv(
"test.csv", usecols=('Author', 'Title', 'Abstract Note', 'Url'))
print(df)
请注意,'Url' 没有按应有的方式位于 df 的最后。
请您参考如下方法:
我认为这是对 usecols 功能的误解。 documentation并不建议列以参数中呈现的相同顺序返回。
usecols : array-like or callable, default None
Return a subset of the columns. If array-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in names or inferred from the document header row(s). For example, a valid array-like usecols parameter would be [0, 1, 2] or [‘foo’, ‘bar’, ‘baz’].
If callable, the callable function will be evaluated against the column names, returning names where the callable function evaluates to True. An example of a valid callable argument would be lambda x: x.upper() in ['AAA', 'BBB', 'DDD']. Using this parameter results in much faster parsing time and lower memory usage.
事实上,这些列返回的顺序与它们在文件中出现的顺序相同。
cols = ['Author', 'Title', 'Abstract Note', 'Url']
with open('test.csv') as fh:
print('\n'.join(filter(lambda x: x in cols, fh.readline().split(','))))
Author
Title
Url
Abstract Note
当我们读取文件时:
df = pd.read_csv(
"test.csv", usecols=('Author', 'Title', 'Abstract Note', 'Url'))
df.columns
Index(['Author', 'Title', 'Url', 'Abstract Note'], dtype='object')
我们看到相同的列顺序。
相反,将生成的数据框按您想要的顺序用列切片。
cols = ['Author', 'Title', 'Abstract Note', 'Url']
df = pd.read_csv('test.csv', usecols=cols)[cols]
df.columns
Index(['Author', 'Title', 'Abstract Note', 'Url'], dtype='object')
