【问题标题】:How do you remove parts of a string in a column using rstrip in Pandas? [duplicate]如何在 Pandas 中使用 rstrip 删除列中的部分字符串? [复制]
【发布时间】:2019-01-30 02:03:36
【问题描述】:

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()

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

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

【问题讨论】:

  • 请将数据框作为文本而不是图像发布
  • rstrip() 从字符列表中删除 any,而不是 all。例如"Hello".rstrip('Ao2') 返回'Hell'
  • 我将其标记为重复,因为 Pandas str 方法行为完全模仿了常规 Python 字符串方法。

标签: python string pandas


【解决方案1】:

这是rstrip 的预期行为:

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

它不只是删除 字符串 _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

【讨论】:

    猜你喜欢
    • 2012-04-18
    • 2022-01-25
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 2019-11-07
    • 2021-12-07
    • 1970-01-01
    • 2018-11-16
    相关资源
    最近更新 更多