使用 python pandas 从 Excel 文件中删除无关数据

问题描述 投票:0回答:1

我收到了一个 Excel 电子表格,其中包含需要使用 python pandas 进行分析的数据。但是,数据的格式无法直接转换为 pandas 数据帧。电子表格的前几行包含描述,后面是需要分析的数据。例如,电子表格可能如下所示:enter image description here

This csv document is not the official valuation. This has been provided to you at your request for your convenience only.                                       
Please refer to the accompanying PDF document for the official valuation statement. "                                       
                                        
For: Company XYZ                                        
                                        
                                                                                                                      Mark to Market    
                                                                                                                          Your Favor    
                                                                           Fixed    Fixed                                (Our Favor)    
  Deal                   Deal   Reference            Start                 Price    Price   Deal         Remaining     Present Value    
  Id                     Date   Commodity            Date       Expiry    Strike     Curr   Type          Quantity               USD        
  ------------------    ------- ----------------    -------     ------- --------    -----   ----    --------------  ----------------        
                                        
                                                                                
Valuations and position directions are from the client point of view                                        
Notice: The information in this document is confidential. 

我需要以一种可以隔离需要分析的数据的方式操作电子表格。我无法将跳过行方法与 read_excel 一起使用,因为文档之间的文本行数可能有所不同。我也无法预处理文档,因为此过程将是自动化的。

任何建议都会有所帮助

python pandas excel
1个回答
0
投票

似乎您有一个块(固定宽度数据),该块在至少两个空行之间分隔。如果总是这样,您可以

split
数据,然后
read_fwf
制作数据框:

import re

with open("file.csv") as f:
    data = re.split(r"^\s+\n\s+?", f.read(), flags=re.M)[1]
    raw = pd.read_fwf(StringIO(data), header=None, comment="-")

N = 5 # the height of the header (columns names)

cols = raw.iloc[:5].fillna("").apply(lambda s: s.str.cat(sep=" ").strip())

df = raw.iloc[5:].set_axis(cols, axis=1)

输出(0行x 10列):

交易 ID 交易日期 参考商品 开始日期 到期 固定价格执行 固定价格当前 交易类型 剩余数量 标记以营销您喜欢的(我们喜欢的)现值美元
© www.soinside.com 2019 - 2024. All rights reserved.