如何用Python合并CSV列并按UniqueID从链接统计总数
解决方案:CSV列合并+网页数据爬取填充
1. 合并A/B/C列为ABC列
利用Pandas的字符串拼接功能,同时处理空值避免报错:
# 合并A、B、C三列,转为字符串并填充空值 new['ABC'] = new['A'].fillna('').astype(str) + new['B'].fillna('').astype(str) + new['C'].fillna('').astype(str) # 可选:调整列顺序,将ABC列前置 new = new[['ABC', 'Total']]
2. 爬取链接获取Serial ID总数
先安装依赖库:
pip install requests beautifulsoup4 pandas
编写爬取函数(需根据目标网页结构调整查找逻辑):
import requests from bs4 import BeautifulSoup def get_serial_id_count(url): try: # 发送请求,设置超时避免卡顿 response = requests.get(url, timeout=10, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}) response.raise_for_status() # 捕获请求错误 soup = BeautifulSoup(response.text, 'html.parser') # -------------------------- # 此处需替换为实际页面的查找逻辑 # 示例1:统计所有class为"serial-id"的元素数量 serial_elements = soup.find_all(class_='serial-id') count = len(serial_elements) # 示例2:匹配页面中"Total Serial IDs: X"格式的数字 # import re # match = re.search(r'Total Serial IDs: (\d+)', response.text) # count = int(match.group(1)) if match else 0 # -------------------------- return count except Exception as e: print(f"处理链接{url}失败: {str(e)}") return 0 # 出错时返回0或NaN
完整整合代码
将上述逻辑嵌入你的现有代码:
import os import pandas as pd import requests from bs4 import BeautifulSoup def get_serial_id_count(url): try: response = requests.get(url, timeout=10, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}) response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') # 替换为你的实际页面查找逻辑 serial_elements = soup.find_all(class_='serial-id') return len(serial_elements) except Exception as e: print(f"Error processing {url}: {str(e)}") return 0 directory = 'C:/Path' ext = ('.csv') output_dir = 'C:/Output' # 确保输出目录存在 os.makedirs(output_dir, exist_ok=True) for filename in os.listdir(directory): f = os.path.join(directory, filename) if f.endswith(ext): # 生成输出文件名 base_name = os.path.splitext(filename)[0] output_path = os.path.join(output_dir, f"{base_name} - Revised.csv") # 读取CSV并处理列 mydata = pd.read_csv(f) new = mydata[["A", "B", "C", "D"]].rename(columns={'D': 'Total'}) # 合并列 new['ABC'] = new['A'].fillna('').astype(str) + new['B'].fillna('').astype(str) + new['C'].fillna('').astype(str) # 填充Serial ID总数 new['Total'] = new['ABC'].apply(get_serial_id_count) # 调整列顺序并保存 new = new[['ABC', 'Total']] new.to_csv(output_path, index=False) print(f"已处理并保存:{output_path}")
关键注意事项
- 必须根据目标网页的实际HTML结构,修改
get_serial_id_count函数中的查找逻辑(用浏览器F12查看页面元素) - 若目标网站有反爬机制,需添加更完整的请求头,或处理Cookie/验证码
- 数据量较大时,可安装
swifter库(pip install swifter),用new['ABC'].swifter.apply(get_serial_id_count)加速处理
内容的提问来源于stack exchange,提问作者QuickSilver42
相关产品推荐
相关产品推荐

