使用pandas和字典的Python查找和替换工具

2024-09-28 21:54:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在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的了解很少。谢谢你的帮助


Tags: the字符串incoordinatedffor字典value
1条回答
网友
1楼 · 发布于 2024-09-28 21:54:52

newvalue never creates and I don't know why.

带有inplace=TrueDataFrame.replace将返回无

>>> df = pd.DataFrame({'Code1': ['ABC1', 'B5CD', 'C3DE']})
>>> df = df.replace('ABC1','999')
>>> df
  Code1
0   999
1  B5CD
2  C3DE
>>> q = df.replace('999','zzz', inplace=True) 
>>> print(q)
None
>>> df
  Code1
0   zzz
1  B5CD
2  C3DE
>>>

另一种方法是b在列上使用str.translate(使用其str attribute)对整个序列进行编码

>>> df = pd.DataFrame({'Code1': ['ABC1', 'B5CD', 'C3DE']})
>>> mydictionary = {'A': 'B', 'B': 'C', 'C': 'D'}
>>> table = str.maketrans('ABC','BCD')
>>> df
  Code1
0  ABC1
1  B5CD
2  C3DE
>>> df.Code1.str.translate(table)
0    BCD1
1    C5DD
2    D3DE
Name: Code1, dtype: object
>>>

相关问题 更多 >