我有一个具有不同列的dataframe(df)。其中一列(col1)如下:
col1
----
0 1
1 2
2 1-2
3 1,2
4 1-3
5 3我在python/大熊猫中使用.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的值,然后在这些值中用字典中的值替换了代码。
这很奇怪,因为我只运行了regex代码/命令一次。
一种解决方案是,我可以使用英语单词代替1-2 more than normal,而不是在字典值中使用数字,我可以写one-two more than normal,然后它就能工作了。但我想保留这些数字,因为它们很容易解释。
有什么建议吗?
发布于 2018-11-09 13:58:28
重复你的工作,我似乎不像你在输入时犯同样的错误
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所以我看不出有什么问题。
除此之外,我将考虑您在这里进行的转换,以及输出的可读性。如果要根据某些预先确定的限制计算每个值,为什么不为每一行创建另一个列,以指示它是哪个分类组的成员?希望这能帮上忙!
https://stackoverflow.com/questions/52273275
复制相似问题