python - 如何从熊猫列中的字符串中删除空格
问题描述
我需要删除 pandas df 列中的空格。我的数据如下所示:
industry magazine
Home "Goodhousekeeping.com"; "Prevention.com";
Fashion "Cosmopolitan"; " Elle"; "Vogue"
Fashion " Vogue"; "Elle"
下面是我的代码:
# split magazine column values, create a new column in df
df['magazine_list'] = dfl['magazine'].str.split(';')
# stip the first whitespace from strings
df.magazine_list = df.magazine_list.str.lstrip()
这将返回所有 NaN,我也尝试过:
df.magazine = df.magazine.str.lstrip()
这也没有删除空格。
解决方案
Jezrael 提供了一个很好的解决方案。知道 pandas 具有类似操作的字符串访问器而不需要列表推导是很有用的。通常,列表推导更快,但根据使用情况,使用 pandas 内置函数可能更具可读性或更易于编码。
df['magazine'] = (
df['magazine']
.str.replace(' ', '', regex=False)
.str.replace('"', '', regex=False)
.str.strip(';')
.str.split(';')
)
输出
industry magazine
0 Home [Goodhousekeeping.com, Prevention.com]
1 Fashion [Cosmopolitan, Elle, Vogue]
2 Fashion [Vogue, Elle]
推荐阅读
- flutter - 如何在颤动中制作全屏警报对话框
- c# - 如何将多个参数从 Angular 8 传递到 .NET Core API
- sql - SQL Server:从该 id 的每个状态中获取 min(lastupdatedate)
- php - 将 json 对象保存为文件中的解码 PHP 数组
- robotframework - Robot Framework - 图像匹配后从区域中提取文本
- python-3.x - Python3 矩阵求和收获
- javascript - 用javascript更改html标签内的文本
- javascript - 需要帮助:如何在不刷新页面的情况下获得一个全新的 wasm 模块实例?
- javascript - 使用外部库构建 Vue 组件以在浏览器中使用
- javascript - window.addEventListener('load', function) 在 react(gatsby) 中不起作用