我确信之前已经提出要求,或者有一个非常简单的答案,但我很难对此进行排查并找到确切的问题。
我有以下代码基本上是抓一个表(它实际上是从用html创建的文本文档中获取数据)而我实际上是在尝试制作表的精确副本。内部for循环应该从第一行创建一个列表,将它附加到pandas数据帧,然后移动到第二行并用新行的值替换列表的值并重复。
from bs4 import BeautifulSoup # imports BeautifulSoup
import pandas # imports pandas
#df=pandas.Dataframe("listname")
#Imports the text file and saves it as a variable
def read_file():
file = open('Detroit.txt')
data = file.read()
file.close()
return data
#Converts the text file into something the
soup = BeautifulSoup(read_file(),'lxml')
tables = soup.find_all(class_="overthrow table_container") #Creates a resutset that will show all of the tables with this class name
find_table = tables[2].tbody #creates a tag element from the desired table and highlights the tbody section
rows = find_table.find_all("tr") #creates another resultset signle out the elements with a tr tag.
list_of_rows = []
df = pandas.DataFrame()
for j in range(len(rows)):
row_finder = rows[j]
tag_row = row_finder.find_all("td")
for i in range(len(tag_row)):
list_of_rows.insert(i,tag_row[i].get_text())
df.append(list_of_rows,ignore_index=True)
print(df)
问题是当我打印数据帧时,我得到了这个结果
Empty DataFrame
Columns: []
Index: []
我无法理解为什么。
答案 0 :(得分:2)
df = df.append(list_of_rows,ignore_index=True)
我不认为它会附加到位,而是返回一个新的df。