python - 如何在 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()
错误:为什么 ID 索引 #1 在末尾删除了值 2,而 rstrip 函数没有请求(该函数仅请求删除“_V2”)?
我很想听听任何有关修复的建议。
解决方案
这是预期的行为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
推荐阅读
- javascript - 如何在谷歌甘特图中添加水平滚动条?
- node.js - Puppeteer 需要很长时间才能加载页面
- cordova - 在 IONIC App 中连接 OTG Device (Pendrive) 并执行 READ/WRITE 操作
- javascript - 写入项目目录中的文件 - React Native
- javascript - Angular Universal 不呈现来自 API 请求的数据
- r - 传单和闪亮的 html 小部件错误呈现
- javascript - 如何在 angularjs 中获取子元素
- http - 如何在 HTTPie 中使用 PUT 上传文件
- php - 使用 PHPExcel 库将 Html 表导出到 Excel 文件时出现乱码
- java - 想要在 spring rest API 中发送文件以及其他一些值