将字符串格式坐标数据导入Excel时遇空DataFrame错误求解决
坐标字符串转Excel/DataFrame的问题解决
问题说明
我有如下格式的坐标字符串:
str1 = "[0,-1.5],[-12.5,1.5],[12.5,1.5],[12.5,-1.5],[-12.5,-1.5])"
需要将每个数组的第一个值存入Excel的X列,第二个值存入Y列,但尝试将字符串转为DataFrame时出现Empty DataFrame错误,使用的代码如下:
bad_chars = [';', ':', '(', ')', '[', ']'] s = "" for i in str1: if i not in bad_chars: s += i print(s) StringData = StringIO(s) df = pd.read_csv(StringData, sep=",") # Print the dataframe print(df)
错误表现:输出Empty DataFrame,列索引为空。
问题原因
原代码处理后得到的字符串是0,-1.5,-12.5,1.5,12.5,1.5,12.5,-1.5,-12.5,-1.5,pd.read_csv按逗号分割后会识别为一行10列的结构,但由于没有指定列名或正确的行结构,最终返回空DataFrame。
解决方法
方法1:手动拆分坐标对构造DataFrame
import pandas as pd from io import StringIO str1 = "[0,-1.5],[-12.5,1.5],[12.5,1.5],[12.5,-1.5],[-12.5,-1.5])" # 清理末尾的右括号,拆分出每个坐标对 cleaned_pairs = str1.strip(')').split('],[') # 处理首尾残留的括号 cleaned_pairs[0] = cleaned_pairs[0].lstrip('[') cleaned_pairs[-1] = cleaned_pairs[-1].rstrip(']') # 遍历拆分每个坐标对为X、Y值 coordinate_list = [] for pair in cleaned_pairs: x_val, y_val = pair.split(',') coordinate_list.append({'X': float(x_val), 'Y': float(y_val)}) # 构造DataFrame并导出到Excel df = pd.DataFrame(coordinate_list) print(df) df.to_excel('coordinates.xlsx', index=False)
方法2:正则表达式提取坐标(更简洁)
import pandas as pd import re str1 = "[0,-1.5],[-12.5,1.5],[12.5,1.5],[12.5,-1.5],[-12.5,-1.5])" # 用正则匹配所有格式为[X,Y]的坐标对 coord_pattern = re.compile(r'\[(-?\d+\.?\d*),(-?\d+\.?\d*)\]') matched_coords = coord_pattern.findall(str1) # 转换为DataFrame并指定列名,导出到Excel df = pd.DataFrame(matched_coords, columns=['X', 'Y']).astype(float) print(df) df.to_excel('coordinates.xlsx', index=False)
内容的提问来源于stack exchange,提问作者ahmad
相关产品推荐
相关产品推荐

