Skip to main content
 首页 » 编程设计

python之迭代循环并将列表添加到新行或新列中的数据框

2024年12月31日9bhlsheji

我确信这很简单,但我是 Python 的新手。我在每次循环迭代后如何将列表添加到数据框列或行时遇到问题。 我想使用外部 for 循环遍历大约一百个 URL 的列表,并使用内部循环提取数据。每一次

现在使用代码,我可以创建一个数据框,将所有列表一起附加到数据框中的一列或一行。但是我希望在数据帧的新列或行中单独进行内部循环的每次迭代。

list_rows = []  
for x in link_href_list:  
    urllib.request.urlopen(x) 
    html = urlopen(x) 
    bs = BeautifulSoup(html, "lxml")     
    table=bs.find('tbody') 
    rows = table.tr.next_siblings 
 
    for row in rows: 
        a=row.find('td').get_text().strip() 
        list_rows.append(a) 
list_rows.to_frame() 

不幸的是,内部循环的列表将有不同的长度! 也许有人有一个简单的解决方案或暗示我可以改变什么?谢谢!

请您参考如下方法:

我假设您的意思是新“行”中外循环的每次迭代。 结果,这将创建一个二维数组(列表),对于 link_href_list 中的每个元素,您将获得一个新的“行”。尽管我不知道 to_frame() 方法是什么,但我认为它是一个打印输出。

list_columns = []  
for x in link_href_list:  
    urllib.request.urlopen(x) 
    html = urlopen(x) 
    bs = BeautifulSoup(html, "lxml")     
    table=bs.find('tbody') 
    rows = table.tr.next_siblings 
    list_rows = [] 
 
    for row in rows: 
        a=row.find('td').get_text().strip() 
        list_rows.append(a) 
    list_columns.append(list_rows) 
list_columns.DataFrame() 

编辑:如果 to_frame 是 pandas DataFrame 的东西,我不完全确定它将如何处理不同的长度。我会检查几个,但也有办法解决这个问题。 似乎手边没有关于如何导入不同长度列表的非常简单的答案,找到最长的列表并相应地调整 pandas 导入并在新循环中制作等长的列表。