Pandas trim 特定的前导字符
Pandas trim specific leading characters
给定以下数据框:
import pandas as pd
import numpy as np
df = pd.DataFrame({
'A' : ['a', 'b','c', 'd'],
'B' : ['and one', 'two','three', 'and four']
})
df
A B
0 a and one
1 b two
2 c three
3 d and four
我想 trim 关闭 'and ' 从以该字符串部分开始的任何单元格的开头。
想要的结果如下:
A B
0 a one
1 b two
2 c three
3 d four
提前致谢!
您可以使用正则表达式 str.replace
:
>>> df
A B
0 a and one
1 b two
2 c three and
3 d and four
>>> df["B"] = df["B"].str.replace("^and ","")
>>> df
A B
0 a one
1 b two
2 c three and
3 d four
(请注意,我在第 2 行的末尾放置了一个 "and",以表明它不会被更改。)
给定以下数据框:
import pandas as pd
import numpy as np
df = pd.DataFrame({
'A' : ['a', 'b','c', 'd'],
'B' : ['and one', 'two','three', 'and four']
})
df
A B
0 a and one
1 b two
2 c three
3 d and four
我想 trim 关闭 'and ' 从以该字符串部分开始的任何单元格的开头。 想要的结果如下:
A B
0 a one
1 b two
2 c three
3 d four
提前致谢!
您可以使用正则表达式 str.replace
:
>>> df
A B
0 a and one
1 b two
2 c three and
3 d and four
>>> df["B"] = df["B"].str.replace("^and ","")
>>> df
A B
0 a one
1 b two
2 c three and
3 d four
(请注意,我在第 2 行的末尾放置了一个 "and",以表明它不会被更改。)