我有一个数据框,其中有一列如下
输入:
CD
Component Description_CAP YO
Component Description_CAPE IO
Component Description_CLOSE SO
Component Description_CAT TO
Component Description_CAPP TTO
Component Description_CLOSE IUO
我使用了lstrip,其中Component_Description后面的“C”被删除,这是错误的
df['CD'] = df['CD'].map(lambda x: x.lstrip('Component Description_'))
预期结果:
CD
CAP YO
CLOSE SO
CAT TO
CAPP TTO
CLOSE IUO
我得到的实际结果
CD
AP YO
LOSE SO
AT TO
APP TTO
LOSE IU
最佳答案
问题出在您的解决方案中,如果使用lstrip
它会从左侧删除字符串中定义的所有字母。
解决方案是使用Series.str.replace
使用 ^
作为正则表达式中的起始字符串:
df['CD'] = df['CD'].str.replace(r'^Component Description_', '')
print (df)
CD
0 CAP YO
1 CAPE IO
2 CLOSE SO
3 CAT TO
4 CAPP TTO
5 CLOSE IUO
关于python - 在 pandas 中使用 lstrip 时删除多余的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57376173/