使用Pandas或其他模块在Python中读取没有隐藏列的Excel文件

时间:2018-03-15 06:01:30

标签: python excel pandas

任何人都可以告诉我如何在Python中使用Pandas或任何其他模块读取没有隐藏列的Excel文件吗?

当我尝试使用Pandas读取excel文件时,例如:

file_np = pd.read_excel(f_name)

dataframe file_np始终包含所有列。从这个数据框中,我不知道如何识别哪个列隐藏在Excel文件中。 谢谢!

1 个答案:

答案 0 :(得分:3)

我认为pandas没有开箱即用。

<强>输入

enter image description here

你不得不做一些冗余阅读(两次)。 openpyxl做你想做的事 -

import openpyxl
import pandas as pd

loc = 'sample.xlsx'
wb = openpyxl.load_workbook(loc)
ws = wb.get_sheet_by_name('Sheet1')

hidden_cols = []
for colLetter,colDimension in ws.column_dimensions.items():
    if colDimension.hidden == True:
        hidden_cols.append(colLetter)

df = pd.read_excel(loc)
unhidden = list( set(df.columns) - set(hidden_cols) )
df = df[unhidden]
print(df)

<强>输出

    C   A
0   1   7
1   9   7
2   5  10
3   7   7
4   4   8
5   4   6
6   9   9
7  10   3
8   1   2

<强>解释

首先使用openpyxl -

读取文件
loc = 'C:/Users/FGB3140/Desktop/sample.xlsx'
wb = openpyxl.load_workbook(loc)
ws = wb.get_sheet_by_name('Sheet1')

在单元格中搜索隐藏属性(这是捕获隐藏列的位置)

hidden_cols = []
for colLetter,colDimension in ws.column_dimensions.items():
    if colDimension.hidden == True:
        hidden_cols.append(colLetter)

使用pandas - df = pd.read_excel(loc)

读取相同的文件

通过从其余列中减去隐藏的列来找到未隐藏的列 -

unhidden = list( set(df.columns) - set(hidden_cols) )

最后,过滤掉未隐藏的列 -

df = df[unhidden]

<强> P.S

我知道我可以完成colDimension.hidden == False或简单if not colDimension.hidden - 此处的目标是捕获隐藏的列,然后相应地进行过滤。希望这有帮助!