【问题标题】:Pandas read_excel ignores blank column that I need to keepPandas read_excel 忽略了我需要保留的空白列
【发布时间】:2021-11-10 17:41:45
【问题描述】:

stackoverflow 的长期用户,第一次发帖,感谢所有帮助 :)

TLDR; 我是否缺少用于保留所有列的 read_excel 参数(即不删除任何列,即使它们是空白的)?

问题详解: 使用 read_excel 时,我有一个空白列作为我正在阅读的一张工作表中的第一列。然后从数据框中删除该空白列,这反过来又弄乱了其余代码,因为它依赖于列索引床单之间是一样的。由于其他表格遵循这种标准化格式,我无法围绕它进行编码。 下面的代码是正确的。在空白列中添加填充值时,代码有效。这不是一个解决方案,因为将列索引 0(A 列)中的空白值设置为某个值所需的逻辑。

Pandas.read_excel documentation

import pandas as pd

df = pd.read_excel(
   "test.xlsx,
   sheet_name = "MYSHEET",
   # Missing parameter that i cannot figure out
)

# Code following this is looping row by row, column by column of each item in dataframe to get desired output

输入的 excel 文件有双标题,A、B、C 列被转为标题值(因此我需要保留空白列)

【问题讨论】:

  • usecols 呢?
  • @BigBen for usecols,对于语法,我将如何指定列 A 到 MV?我在网上找到了一些示例,但它们似乎不起作用。示例:usecols=["A", "MV"] 不起作用。
  • usecols='A:MV',如docs 中所述。
  • 谢谢 - 这似乎已经解决了问题。请将此作为答案发布,以便我可以接受它作为已接受的答案:)

标签: python excel pandas dataframe


【解决方案1】:

看来你可以使用usecols:

df = pd.read_excel(
   "test.xlsx",
   sheet_name="MYSHEET",
   usecols="A:MV"
)

【讨论】:

    【解决方案2】:

    这应该可以解决问题。

    df = pd.read_excel(
       "test.xlsx,
       sheet_name = "MYSHEET",
       skip_blank_lines=False
    )
    

    【讨论】:

    • 遗憾的是,事实并非如此。还有其他选择吗? TypeError: read_excel() got an unexpected keyword argument 'skip_blank_lines'
    • 看起来 skip_blank_lines 已从 read_excel() 中弃用。它仍然适用于 read_csv()。
    • 嗯,那是有道理的。我真的很感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2019-01-23
    • 2019-05-07
    相关资源
    最近更新 更多