正则表达式用列中的值替换多个代码

时间:2018-09-11 09:52:31

标签: python string pandas dictionary

我有一个带有不同列的dataframe(df)。列(col1)之一如下:

    col1
    ----
0   1
1   2
2   1-2
3   1,2
4   1-3
5   3

我正在使用python / pandas中的.replace方法替换使用代码的col1中的代码:

 df.col1.replace(to_replace=({'1':'Normal','2':'1-2 more than normal','3':'3-4 more than normal'}), regex=True)

我使用regex=True是因为在单元格中有1-2这样的代码,其中1和2具有不同的含义,如字典中所述。

输出

    col1
    --------
0   Normal
1   1-2 more than normal
2   Normal-1-2 more than normal
3   Normal,1-2 more than normal
4   Normal-1-2 more than normal-3 more than normal
5   1-2 more than normal-3 more than normal

所需的输出

    col1
    --------
0   Normal
1   1-2 more than normal
2   Normal-1-2 more than normal
3   Normal,1-2 more than normal
4   Normal-3-4 more than normal
5   3-4 more than normal

问题:

如果我不考虑第四行(1-3),那么除代码3外,所有代码均已正确替换。我进一步尝试添加仅包含代码3的行,在那里我发现regex首先替换了代码3的值,然后用这些值替换字典中的值。

很奇怪,因为我只运行一次正则表达式代码/命令。

一种解决方案是,我可以使用英文单词,例如在字典值中使用数字,而不是使用数字。我可以写1-2 more than normal而不是写one-two more than normal,然后它可以工作。但我想保留数字,因为它们易于解释。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

重复您的工作我似乎并没有得到与输入相同的错误

df = pd.DataFrame({'col1' : ['1', '2', '1-2', '1,2', '1-3', '3']})

并应用相同的.replace方法:

df.col1.replace(to_replace=({'1':'Normal','2':'1-2 more than normal','3':'3-4 more than normal'}), regex=True)

我的输出与您所需的输出匹配

输出:

    col1
    ---------
0   Normal
1   1-2 more than normal
2   Normal-1-2 more than normal
3   Normal,1-2 more than normal
4   Normal-3-4 more than normal
5   3-4 more than normal

所以我真的看不到任何问题。

除此之外,尽管我会考虑您在这里进行的转换以及输出的可读性。如果要根据某个预先确定的限制评估每个值,为什么不为每一行创建一个带有标签的列,以指示该列是哪个分类组?希望有帮助!