在python中构建查找和替换工具时遇到问题。目标是在excel文件中搜索一列字符串,并根据字典的键值对交换字符串中的每个字母,然后将整个新字符串写回同一单元格。所以“ABC”应该转换成“BCD”。我必须找到并替换出现的任何单个字符
下面的代码在没有调试的情况下运行,但newvalue从未创建,我不知道为什么。如果创建了newvalue,则不会向单元格写入数据
输入:df=pd.DataFrame({'Code1':['ABC1','B5CD','C3DE']})
预期输出:df=pd.DataFrame({'Code1':['BCD1','C5DE','D3EF']})
mycolumns = ["Col1", "Col2"]
mydictionary = {'A': 'B', 'B': 'C', 'C': 'D'}
for x in mycolumns:
# 1. If the mycolumn value exists in the headerlist of the file
if x in headerlist:
# 2. Get column coordinate
col = df.columns.get_loc(x) + 1
# 3. iterate through the rows underneath that header
for ind in df.index:
# 4. log the row coordinate
rangerow = ind + 2
# 5. get the original value of that coordinate
oldval = df[x][ind]
for count, y in enumerate(oldval):
# 6. generate replacement value
newval = df.replace({y: mydictionary}, inplace=True, regex=True, value=None)
print("old: " + str(oldval) + " new: " + str(newval))
# 7. update the cell
ws.cell(row=rangerow, column=col).value = newval
else:
print("not in the string")
else:
# print(df)
print("column doesn't exist in workbook, moving on")
else:
print("done")
wb.save(filepath)
wb.close()
我知道enumerate发生了一些事情,在我进行替换之后,我可能不会将字符串重新缝合在一起?或者,对于我正在尝试做的事情,字典是一个错误的解决方案,关键:值对是我使用它的原因。我有一点编程背景,但对python的了解很少。谢谢你的帮助
带有
inplace=True
的DataFrame.replace将返回无另一种方法是b在列上使用str.translate(使用其str attribute)对整个序列进行编码
相关问题 更多 >
编程相关推荐