python - 删除pandas df中每一行的字符串中的最后一个字符
问题描述
我有一个带有 column 的熊猫数据框keys
,我需要从每个字符串中删除最后一个字符。
id keys
123 "https://www.cosmopolitan.com/entertainment/tv/a46533/"
124 "https://www.bazaar.com/entertainment/tv/a46533/"
目前,我正在尝试创建一个返回干净字符串的函数,稍后我会将该函数应用于 df 。我尝试了以下方法:
url_test = "https://www.cosmopolitan.com/entertainment/tv/"
def clean_string(url):
for string in url:
new_string = string[:-1]
return new_string
clean_string(url_test)
它返回一个空字符串。我希望它回来"url_test = "https://www.cosmopolitan.com/entertainment/tv"
解决方案
您可以使用 pandas字符串访问器方法
例如
import pandas as pd
test = pd.Series([
"https://www.cosmopolitan.com/entertainment/tv/a46533/",
"https://www.bazaar.com/entertainment/tv/a46533/"])
test = test.str[:-1]
将修剪字符串中的最后一个字符。这使您可以对整列进行操作,而不是一次操作一行。
推荐阅读
- proxy - iOS 13 Burp Suite 代理无法连接
- php - PHP | 来自 SQL 数据库的饼图
- java - 如何创建安全的 vaadin 14 登录表单?
- c - linux中两个虚拟内存如何指向同一个物理内存
- python - 如何在深度学习模型中训练不同尺度的特征
- algorithm - 谷歌量子霸权——一万年是如何假设的?
- jquery - 有没有办法在每个 iframe 中获取父 css 链接 rel?
- git - Git状态查看仅包含空格的文件会更改吗?
- spring-boot - 如何从 web.xml 在 weblogic.xml 中引入路径变量?
- c++ - Boost.Beast 限速