问题描述
我有一个csv文件,使用read_csv
时是否有可能让usecols
占用除最后一列以外的所有列,而没有列出所需的每一列.
I have a csv file, is it possible to have usecols
take all columns except the last one when utilizing read_csv
without listing every column needed.
例如,如果我有13列文件,则可以执行usecols=[0,1,...,10,11]
. usecols=[:-1]
会给我语法错误吗?
For example, if I have a 13 column file, I can do usecols=[0,1,...,10,11]
. Doing usecols=[:-1]
will give me syntax error?
还有其他选择吗?我正在使用pandas 0.17
Is there another alternative? I'm using pandas 0.17
推荐答案
您可以使用 nrows=1
以获取cols,然后通过从第一次读取的列数组中切出列数组来重新读取完整的csv,从而跳过最后一个col: >
You can just read a single line using nrows=1
to get the cols and then re-read in the full csv skipping the last col by slicing the column array from the first read:
cols = pd.read_csv(file, nrows=1).columns
df = pd.read_csv(file, usecols=cols[:-1])
这篇关于 pandas usecols除了最后一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!