如何在含300列的不规则DataFrame中提取指定属性值?
处理不规则大列数DataFrame提取特定属性的最优方法
针对你这种有300列、属性分散在不同列的不规则DataFrame,核心思路是拆分单元格键值对+定向提取目标属性,以下是两种常见需求的高效实现方案(基于Python pandas):
方案1:提取目标属性为列表
直接收集所有目标属性的值,适合快速查看或后续统计分析:
单属性提取(如ID)
import pandas as pd # 构造示例DataFrame(替换为你的实际数据) data = { 'Column1': ['Color=Blue', 'Location=USA', 'ID=987'], 'Column2': ['Location=USA', 'ID=123', 'Name=Gary'], 'Column3': ['Name=Steve', 'Name=Randy', 'Color=Red'], 'Column5': ['N/A', 'Color=Purple', 'Location=Italy'] } df = pd.DataFrame(data) target_attr = 'ID' attr_values = [] # 遍历所有单元格,拆分键值对并收集目标属性 for col in df.columns: for cell in df[col]: if cell != 'N/A': # 跳过空值,若实际是NaN则用pd.isna(cell)判断 key, value = cell.split('=', 1) # 只拆分第一个=,避免值含=的情况 if key == target_attr: attr_values.append(value) print(f"{target_attr}={attr_values}") # 输出:ID=['987', '123']
多属性提取(如Color+ID)
用字典批量收集多个属性的值:
target_attrs = ['Color', 'ID'] attr_dict = {attr: [] for attr in target_attrs} for col in df.columns: for cell in df[col]: if cell != 'N/A': key, value = cell.split('=', 1) if key in attr_dict: attr_dict[key].append(value) for attr, values in attr_dict.items(): print(f"{attr}={values}") # 输出: # Color=['Blue', 'Purple', 'Red'] # ID=['987', '123']
方案2:生成保留原结构的过滤DataFrame
仅保留原表格中目标属性的单元格内容,其余置空,适合对比原数据位置:
target_attr = 'ID' # 定义单元格过滤函数 def filter_target_attr(cell): if cell == 'N/A': return '' key, _ = cell.split('=', 1) return cell if key == target_attr else '' # 应用到整个DataFrame filtered_df = df.applymap(filter_target_attr) # 输出为markdown表格(和你示例格式一致) print(filtered_df.to_markdown(index=False))
输出结果:
| Column1 | Column2 | Column3 | Column5 |
|---|---|---|---|
| ID=123 | |||
| ID=987 |
优化说明
- 效率:遍历+拆分的方式对300列的DataFrame足够高效,若数据量极大(百万级行),可改用
df.stack()扁平化数据后处理,进一步提升速度。 - 兼容性:若单元格存在
NaN而非N/A,将判断条件改为pd.isna(cell)即可;若值中包含=,split('=',1)确保只拆分属性名和值的分隔符。
内容的提问来源于stack exchange,提问作者NRH
相关产品推荐
相关产品推荐

