小编thr*_*eam的帖子

从具有复杂逻辑的单列创建多列

我对数据框和/或系列的所有 apply、applymap、map 内容感到有点困惑。我想通过执行一些网络抓取操作的函数创建从数据框中的一列派生的多个列。

我的数据框看起来像这样

>>> df
          row1        url    row3
0        data1  http://...    123
1        data2  http://...    325
2        data3  http://...    346
Run Code Online (Sandbox Code Playgroud)

网页抓取功能是这样的

def get_stuff_from_url(url: str):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    data1 = soup.find('div', {'class': 'stuff1'})
    data2 = soup.find('span', {'class', 'stuff2'}).text
    data3 = soup.find('p', {'class', 'stuff3'}).text

    return data1, data2, data3
Run Code Online (Sandbox Code Playgroud)

结果应该是

>>> df_new
          row1        url    row3       row4       row5       row6
0        data1  http://...    123  newdata1a  newdata2a  newdata3a
1        data2  http://...    325  newdata1b  newdata2b  newdata3b
2        data3  http://...    346  newdata1c  newdata2c …
Run Code Online (Sandbox Code Playgroud)

python beautifulsoup dataframe web-scraping pandas

1
推荐指数
1
解决办法
471
查看次数

标签 统计

beautifulsoup ×1

dataframe ×1

pandas ×1

python ×1

web-scraping ×1