[英]string replace method in pandas gives an unexpected result
I'm trying to change the values of 35 000 rows on a DataFrame using the string replace method.我正在尝试使用字符串替换方法更改 DataFrame 上 35 000 行的值。 However, my solution does not return what I want and I can't figure out why it fails.
但是,我的解决方案没有返回我想要的,我无法弄清楚它为什么会失败。 Here is a simple example of the data frame:
这是数据框的一个简单示例:
import pandas as pd
liste = ['1_8','1_8','1_8','1_8','1_8','1_8','1_9', '1_9', '1_9','1_9','1_10','1_10','1_10','1_10','1_10','1_10','1_11','1_11']
mycooldataframe = pd.DataFrame(liste, columns =['bib'])
print(mycooldataframe)打印(mycooldataframe)
bib
0 1_8
1 1_8
2 1_8
3 1_8
4 1_8
5 1_8
6 1_9
7 1_9
8 1_9
9 1_9
10 1_10
11 1_10
12 1_10
13 1_10
14 1_10
15 1_10
16 1_11
17 1_11
I want to change 1_8 so that it becomes 108. Similarly, I want to replace 1_11 so that it becomes 110. I have tried to solve this using:我想更改 1_8 使其变为 108。同样,我想替换 1_11 使其变为 110。我尝试使用以下方法解决此问题:
mycooldataframe['bib'] = mycooldataframe['bib'].str.replace('1_8', '108')
, which works fine. ,效果很好。 It gives me 108. But if I use:
它给了我 108。但是如果我使用:
mycooldataframe['bib'] = mycooldataframe['bib'].str.replace('1_10', '110')
that gives me 1010. Why doesn't it work?这给了我 1010。为什么它不起作用? Is there a better way to solve this problem.
有没有更好的方法来解决这个问题。 I appreciate your help.
我感谢您的帮助。
The code in your example works as expected.您示例中的代码按预期工作。 If you're having issues with other cases, you can try using a dictionary:
如果您在其他情况下遇到问题,可以尝试使用字典:
value_map = {'1_8':'108', '1_10':'110'}
mycooldataframe= mycooldataframe.replace(value_map)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.