Python Zip 列表到 Dataframe

标签 python dataframe

我想从 html 中压缩一些列表,我使用如下代码:

html_link = 'https://www.pds.com.ph/index.html%3Fpage_id=3261.html'
html = requests.get(html_link).text
soup = BeautifulSoup(html, 'html.parser')

search = re.compile(r"March.+2021")

for td in soup.find_all('td', text=search):
    link = td.parent.select_one("td > a")

    if link:
        titles = link.text
        links = f"Link : 'https://www.pds.com.ph/{link['href']}"
        dates = td.text
for link, title, date in zip(links, titles, dates):
    dataframe = pd.DataFrame({'col1':title,'col2':link,'col3':date},index=[0])
    print(dataframe)

但是输出不是我所期望的:

col1 col2 col3
1    P    L    M
  col1 col2 col3
1    D    i    a
...

我的期望是:

Titles Links Dates
...    ...    ...

请问语法是否正确或者我可以做什么来实现这一点?

最佳答案

您可以将 zip 的结果直接传递到 pd.DataFrame,并在列表中指定列名称:

df = pd.DataFrame(zip(titles, links, dates), columns=['Titles', 'Links', 'Dates'])

关于Python Zip 列表到 Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67411124/

相关文章:

javascript - 使用 ReactJS 和 python Flask。一般的做法

python - 错误: 502 bad gateway in flask app on nginx and uwsgi

python - 如何在python中将一个键对值从一个字典复制到另一个字典

python - 迁移重命名模型字段ManyToMany Django 1.8

python - 根据数据帧列中的值绘制直方图

python - 在Python中用数据帧中的平均值替换 '?'时出错

python - 将 1300 个数据帧按列合并成一个帧变得非常慢

python - 如何将数据重新组织到 pandas 中的新数据框中,以这种方式显示数据的更改?

python - DataFrame 从列表转置

python - 如何在PDF文件末尾添加空白页?