读取excel框架时跳过特定的一组列 - 熊猫

Jua*_*vid 10 python excel python-3.x pandas

我事先知道我不需要 excel 文件中的哪些列,我想在读取文件时避免使用它们以提高性能。像这样的东西:

import pandas as pd
df = pd.read_excel('large_excel_file.xlsx', skip_cols=['col_a', 'col_b',...,'col_zz'])
Run Code Online (Sandbox Code Playgroud)

文档中没有与此相关的内容。有什么解决方法吗?

Mar*_*ews 14

如果您的 Pandas 版本允许(首先检查您是否可以将函数传递给 usecols),我会尝试以下操作:

import pandas as pd
df = pd.read_excel('large_excel_file.xlsx', usecols=lambda x: 'Unnamed' not in x,)
Run Code Online (Sandbox Code Playgroud)

这应该跳过所有没有标题名称的列。您可以将“未命名”替换为您不需要的列名列表。

  • 请注意,`usecols`接受列字母作为参数:usecols = "A,C:AA" (2认同)

Max*_*axU 11

您可以使用以下技术。让我们不想要的列(要跳过)为2 5 8,然后找到大家都reamining列DO要保持cols这样:

In [7]: cols2skip = [2,5,8]  
In [8]: cols = [i for i in range(10) if i not in cols2skip]

In [9]: cols
Out[9]: [0, 1, 3, 4, 6, 7, 9]
Run Code Online (Sandbox Code Playgroud)

然后我们可以使用那些剩余的列(我们确实想要保留)usecols

df = pd.read_excel(filename, usecols=cols)
Run Code Online (Sandbox Code Playgroud)