加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何从pandas read_html重新索引格式错误的列?

发布时间:2020-12-16 22:46:03 所属栏目:Python 来源:网络整理
导读:我正在从一个网站中检索一些内容,这些网站有几个具有相同列数的表,使用pandas read_html .当我读取一个实际上有几个具有相同列数的表的链接时,pandas有效地将所有表读为一个(类似平面/标准化表格的东西.但是,我有兴趣对网站的链接列表(即几个链接的单个平面

我正在从一个网站中检索一些内容,这些网站有几个具有相同列数的表,使用pandas read_html.当我读取一个实际上有几个具有相同列数的表的链接时,pandas有效地将所有表读为一个(类似平面/标准化表格的东西.但是,我有兴趣对网站的链接列表(即几个链接的单个平面表)执行相同的操作,因此我尝试了以下操作:

在:

import multiprocessing
def process(url):
    df_url = pd.read_html(url)
    df = pd.concat(df_url,ignore_index=False) 
    return df_url

links = ['link1.com','link2.com','link3.com',...,'linkN.com']

pool = multiprocessing.Pool(processes=6)
df = pool.map(process,links)
df

尽管如此,我想我并没有指定core_cts的corecctly,因此我得到了这个列表格式错误的列表:

日期:

[[                Form     Disponibility  
  0  290090 01780-500-01)  Unavailable - no product available for release.   

                             Relation  

     Relation drawbacks  
  0                  NaN                        Removed 
  1                  NaN                        Removed ],[                                        Form  

                                   Relation  
  0  American Regent is currently releasing the 0.4...   
  1  American Regent is currently releasing the 1mg...   

     drawbacks  
  0  Demand increase for the drug  
  1                         Removed,Form  
  0  0.1 mg/mL; 10 mL Luer-Jet Prefilled Syringe (N...   

    Disponibility  Relation  
  0                            Product available                  NaN   
  2                        Removed 
  3                        Removed ]]

所以我的问题是我应该移动哪个参数才能从上面的嵌套列表中获得平坦的pandas数据帧?我尝试使用header = 0,index_col = 0,match =’“columns”’,它们都没有工作,或者当我用pd.Dataframe()创建pandas数据帧时,我是否需要进行平面化?我的主要目标是拥有一个像这个列一样的pandas数据框:

form,Disponibility,Relation,drawbacks
1 
2
...
n
最佳答案
IIUC你可以这样做:

首先,您要返回连接的DF,而不是DF的列表(因为read_html返回DF的列表):

def process(url):
    return pd.concat(pd.read_html(url),ignore_index=False) 

然后为所有URL连接它们:

df = pd.concat(pool.map(process,links),ignore_index=True)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读