簡體   English   中英

迭代循環並將列表添加到新行或新列中的數據框

[英]Iterate over loop and adding list to dataframe in new row or new column

我確定這很簡單,但我對 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 的東西,我不完全確定它將如何處理不同的長度。 我會登記一對夫婦,但也有辦法解決這個問題。 似乎沒有關於如何導入不同長度列表的非常簡單的答案,並找到最長的列表並相應地調整熊貓導入並在新循環中制作等長的列表。

一種方法是在外面創建一個空列表,然后在循環內附加,您已經嘗試過了。 您的問題似乎是創建數據框。 我會在上面的答案下發表評論以供其他人參考,但是我不能在此代表處發表評論。

定義您的列,然后使用from_records創建數據from_records

 import pandas as pd
 cols = ['col_1','col_2',...,'col_n']
 df = pd.DataFrame.from_records(list_cols, columns=cols)

上面的答案創建了一個列表( list_columns = [] ),然后嘗試轉換為 Dataframe。 這應該拋出以下內容:

 Traceback (most recent call last):
   File "<ipython-input-396-dc539f26ae12>", line 1, in <module>
    list_columns.Dataframe()

 AttributeError: 'list' object has no attribute 'Dataframe'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM