Python解析浮点字符串并从Pandas DataFrame提取匹配列对应值
实现思路
- 针对每个单元格的字符串,先按分号拆分得到多个四元组
- 每个四元组按逗号拆分后,以第一个值为键、第三个值为值,存入字典
- 把所有行生成的字典批量转为DataFrame,自动匹配键为列名,填充对应值
完整实现代码
import pandas as pd # 原始数据构造,规避使用list作为变量名(Python内置关键字) raw_data = [['10, 0.01, 0.0428, 120; 30, 0.1, 2, 33; 50, 0.023, 0.31, 0.65'], ['10, 0.7, 0.5428, 2.31'], ['50, 0.3, 0.35, 0.1'], ['-10, 0.2, 0.048, 124; -30, 0.11, 24, 3; -50, 0.02, 0.1, 0.60; 0, 0, 0, 0; 10, 0.1, 2, 33; 20, 0.023, 0.31, 0.66']] df = pd.DataFrame(raw_data) # 单元格解析函数 def parse_cell(content): res_map = {} for group in content.split(';'): group = group.strip() if not group: continue parts = [p.strip() for p in group.split(',')] if len(parts) == 4: res_map[parts[0]] = parts[2] return res_map # 生成结果表 result_df = pd.json_normalize(df[0].apply(parse_cell)) # 可选:将值转为浮点类型 result_df = result_df.astype(float) # 可选:按列名的数值大小排序列顺序,更符合阅读习惯 result_df = result_df.reindex(sorted(result_df.columns, key=lambda x: int(x)), axis=1)
运行后得到的result_df完全符合预期输出要求,无匹配值的位置自动填充为NaN。
内容的提问来源于stack exchange,提问作者newman
相关产品推荐
相关产品推荐

