首页 > 解决方案 > 如何在 Pandas 中使用 rstrip 删除列中的部分字符串?

问题描述

rstrip之前的代码

column_names = lh_Area_Base_V2.columns.tolist()
for i, val in enumerate(column_names[1:]):
    column_names[i+1] += '_Base_V2'
column_names[0] = 'Subj_ID'
# Replace the column names with a new name
lh_Area_Base_V2.columns = column_names
lh_Area_Base_V2.head()

初始自由度

带有 rstrip 的代码(从第一列值的末尾删除“_V2”):

column_names = lh_Area_Base_V2.columns.tolist()
for i, val in enumerate(column_names[1:]):
    column_names[i+1] += '_Base_V2'
column_names[0] = 'Subj_ID'
lh_Area_Base_V2['Subj_ID'] = lh_Area_Base_V2['Subj_ID'].map(lambda x: x.lstrip().rstrip('_V2'))
# Replace the column names with a new name
lh_Area_Base_V2.columns = column_names
lh_Area_Base_V2.head()

rstrip后的结果DF

错误:为什么 ID 索引 #1 在末尾删除了值 2,而 rstrip 函数没有请求(该函数仅请求删除“_V2”)?

我很想听听任何有关修复的建议。

标签: pythonstringpandas

解决方案


这是预期的行为rstrip

chars 参数是一个字符串,指定要删除的字符集

它不仅仅是剥离string _V2,它还会剥离任何包含的字符,包括2第二行末尾的 。

相反,您可以使用正则表达式来替换尾随_V2

df.assign(Subj_ID=df.Subj_ID.str.replace(r'_V2$', ''))

    Subj_ID  lh_bankssts_area_base_V2
0  SILVA001                       861
1  SILVA002                      1051
2  SILVA004                      1127
3  SILVA005                      1346
4  SILVA007                      1209

推荐阅读