如何去除Python Pandas输出中的[]与''符号以适配pyautogui.typewrite?
问题描述
尝试从Excel表格解析数据并存储到数组中,后续用于pyautogui.typewrite()调用,但输出始终带有[]和''符号。试过.remove()、split()、tolist()、str.join等方法都没解决,期望将数据转为无多余符号的逗号分隔字符串。
当前代码
## OPENING FILES ## # Opens the path to the prints entries = Path(r'C:\Users\jmcintosh\LIDT Project (copy)\LIDT Project\Solidworks Test (DEV)') # Opens excel sheet for reading xlEntries = pd.read_excel(r'C:\Users\jmcintosh\LIDT Project (copy)\LIDT Project\LIDT New Webspec Titles 2.0.xlsx') partNumbers = [] # Make partNumbers the array for partnumbers, gathers the names as well as the partnumbers # For loop that allow iteration through the directory of names. for entry in entries.iterdir(): partNumbertemp = re.findall('[0-9]+', entry.name) partNumbers.append(int(partNumbertemp[0])) # Appends the array with the regex function to parse only the integers of the file name to be used later. # While loop to remove blank file names from directory issues while ([] in partNumbers): partNumbers.remove([]) rowNumber= [] specName= [] specValue= [] rowNumbertemp = [] specNametemp =[] specValuetemp =[] k = 0 while (k<fileCount): #uses partnumbers to check if the index of the array is in the column rowNumbertemp.append(xlEntries.loc[xlEntries['StockNumber'] == partNumbers[k]].index.to_numpy()) rowNumber.append(rowNumbertemp[k]) # in the same row it grabs the specific cell value from another column specNametemp = (xlEntries.loc[rowNumber[k],"Pat's Proposed Change"].tolist()) specName.append(str(specNametemp)) # in the same row it grabs the specific cell value from another column specValuetemp = (xlEntries.loc[rowNumber[k],"StringValue"].tolist()) specValue.append(str(specValuetemp)) k = k + 1 print(specValue) print(specName)
当前输出示例
["['7.5 J/cm² @ 355nm, 20ns, 20Hz']", "['10 J/cm² @ 532nm, 20ns, 20Hz']", "['15 J/cm² @ 1064nm, 20ns, 20Hz']", ..., '[]'] ["['damage threshold, certified']", ..., '[]']
期望输出示例
damage threshold, certified,damage threshold, certified, ... 7.5 J/cm² @ 355nm, 20ns, 20Hz, ...
问题原因
- 调用
.tolist()后,单个单元格值会被包装成列表(比如[值]),再用str()转换就会保留[]和''符号; - 空行对应的列表会被转成字符串
'[]',混入结果中; rowNumber的处理过于复杂,且用to_numpy()返回的是数组,后续loc查询存在冗余。
解决方案
1. 简化数据提取逻辑,直接获取单元格值
不需要用.tolist()再转字符串,而是直接提取单个单元格的原始值。由于每个StockNumber对应唯一行,可通过.iloc[0]直接取值,同时处理空值情况。
2. 修改后的代码
## OPENING FILES ## from pathlib import Path import pandas as pd import re entries = Path(r'C:\Users\jmcintosh\LIDT Project (copy)\LIDT Project\Solidworks Test (DEV)') xlEntries = pd.read_excel(r'C:\Users\jmcintosh\LIDT Project (copy)\LIDT Project\LIDT New Webspec Titles 2.0.xlsx') partNumbers = [] for entry in entries.iterdir(): partNumbertemp = re.findall('[0-9]+', entry.name) if partNumbertemp: # 避免空列表导致索引报错 partNumbers.append(int(partNumbertemp[0])) # 原while循环无效(partNumbers中都是int,不会存在[]),直接删除 # while ([] in partNumbers): # partNumbers.remove([]) specName = [] specValue = [] fileCount = len(partNumbers) # 补充定义fileCount,避免未定义报错 k = 0 while k < fileCount: # 直接筛选匹配行,无需单独存储rowNumber match_row = xlEntries[xlEntries['StockNumber'] == partNumbers[k]] if not match_row.empty: # 提取单个单元格值,而非生成列表 spec_name_val = match_row["Pat's Proposed Change"].iloc[0] spec_value_val = match_row["StringValue"].iloc[0] # 仅添加非空值,避免空字符串混入 if pd.notna(spec_name_val): specName.append(str(spec_name_val)) if pd.notna(spec_value_val): specValue.append(str(spec_value_val)) k += 1 # 将列表转为无多余符号的逗号分隔字符串 final_specName = ','.join(specName) final_specValue = ','.join(specValue) print(final_specName) print(final_specValue)
3. 关键修改点
- 移除冗余的
rowNumber相关变量,直接通过筛选结果提取值; - 用
.iloc[0]获取单个单元格值,避免生成带括号的列表; - 加入
pd.notna()空值判断,跳过空单元格; - 最后用
','.join()直接将列表转为目标格式字符串; - 修复原代码中
fileCount未定义的问题,同时在提取partNumbertemp时加入非空判断,避免索引报错。
内容的提问来源于stack exchange,提问作者Jaiven McIntosh
相关产品推荐
相关产品推荐

