如何在Pandas循环合并DataFrame时添加对应列值?
问题解决:为每个子表添加对应列值
问题背景
用Pandas从多个URL抓取表格数据,需要给每个子表的所有行添加对应列表中的一个值作为新列,最终合并后的表格中,同一子表的所有行都带有相同的对应值。
当前使用版本:
- pandas: 1.3.1
- python: 3.8.0
当前代码:
result_table = [] for url in urls_list: response = s2.get(url=url, headers=headers) soup2 = BS(response.text, 'lxml') try: table = pd.read_html(url) except: print('table not exist') continue result_table.append(table) final_table = pd.DataFrame() for t in result_table: final_table = final_table.append(t) final_table.to_excel("razmeri.xlsx")
当前final_table结构:
| 序号 | 子表行数据 |
|---|---|
| 1 | RowTable1 |
| 2 | RowTable1 |
| 3 | RowTable2 |
| 4 | RowTable2 |
| ... | ... |
期望的final_table结构(假设目标列表为['259', '178', '305', ...]):
| 对应值 | 子表行数据 |
|---|---|
| 259 | RowTable1 |
| 259 | RowTable1 |
| 178 | RowTable2 |
| 178 | RowTable2 |
| 305 | RowTable3 |
| 305 | RowTable3 |
解决方案
修改代码如下,关键是在抓取每个子表时直接添加对应列值,再合并:
# 注意:不要用list作为变量名,替换为target_list,确保长度和有效子表数量匹配 target_list = ['259', '178', '305', ...] result_table = [] # 用enumerate跟踪索引,匹配target_list中的值 for idx, url in enumerate(urls_list): response = s2.get(url=url, headers=headers) soup2 = BS(response.text, 'lxml') try: # pd.read_html返回的是DataFrame列表,取第一个表格(根据实际情况调整索引) df = pd.read_html(url)[0] # 添加新列,整列填充target_list中对应索引的值 df['对应值'] = target_list[idx] result_table.append(df) except Exception as e: print(f'table not exist for url {url}: {e}') # 如果当前URL没有表格,需要从target_list中移除对应值,避免索引错位 del target_list[idx] continue # 用pd.concat合并所有子表,比循环append高效 final_table = pd.concat(result_table, ignore_index=True) final_table.to_excel("razmeri.xlsx", index=False)
关键说明
- 修正pd.read_html的使用:
pd.read_html(url)返回的是DataFrame的列表,需要取对应索引的DataFrame(通常是[0],如果页面有多个表格则调整),否则后续append的是列表,会导致合并出错。 - 匹配列表值与子表:用
enumerate遍历urls_list,同时获取索引对应target_list中的值;如果有URL跳过(无表格),同步删除target_list中对应索引的值,避免索引错位。 - 高效合并:使用
pd.concat代替循环append,数据量大时性能更优,ignore_index=True可重置合并后的索引,避免索引重复。 - 变量命名规范:不要用
list作为变量名,会覆盖Python内置的list类型,引发潜在问题。
内容的提问来源于stack exchange,提问作者Julia
相关产品推荐
相关产品推荐

