简体   繁体   English

Python For循环DataFrame

[英]Python For Loop DataFrame

see below the following code I have at the moment and the error that is coming with it. 请参阅以下我现在拥有的以下代码以及随之而来的错误。

 companynames = []
for x in urls:
    website_nametext = requests.get(x)
    all_text = website_nametext.text
    all_soup = BeautifulSoup(all_text, 'html.parser')
    companynames.append(all_soup.h1.get_text())
overall_data = pd.DataFrame(data=[companynames], columns=['Company Name'])

I receive the following error 我收到以下错误

AssertionError: 1 columns passed, passed data had 3 columns

If I was to change the code to put three columns then it allows the dataframe to be created. 如果要更改代码以放置三列,则可以创建数据框。 See below the code. 参见下面的代码。

    companynames = []
for x in urls:
    website_nametext = requests.get(x)
    all_text = website_nametext.text
    all_soup = BeautifulSoup(all_text, 'html.parser')
    companynames.append(all_soup.h1.get_text())
overall_data = pd.DataFrame(data=[companynames], columns=['Company Name', 'Company Name', 'Company Name'])

However I want the results 'x' , 'y' and 'z' to be in one column and each name on a separate row. 但是,我希望结果“ x”,“ y”和“ z”在同一列中,并且每个名称都在单独的行中。 rather than there being three separate columns as per my initial code however obviously that is creating an error. 而不是按照我的初始代码分成三列,但是显然这会产生错误。

How do I do so? 我该怎么做?

Try taking out the square brackets around companynames in the pd.DataFrame call. 尝试在pd.DataFrame调用中删除公司名称周围的方括号。 With the brackets there it is a list of lists, albeit only one, but it effectively turns it through 90 degrees. 有方括号的是一个列表列表,尽管只有一个,但实际上将其旋转了90度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM