如何使用Pandas/Python删除括号和所有数据? [英] How to remove parentheses and all data within using Pandas/Python?

查看:1303
本文介绍了如何使用Pandas/Python删除括号和所有数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,我想在其中删除所有括号和里面的东西.

I have a dataframe where I want to remove all parentheses and stuff inside it.

我已签出: 如何使用正则表达式删除括号内的文本?

删除数据的答案在哪里

re.sub(r'\([^)]*\)', '', filename)

我也尝试过

re.sub(r'\(.*?\)', '', filename)

但是,我收到一个错误:expected a string or buffer

However, I got an error: expected a string or buffer

当我尝试使用列df['Column Name']时,我得到了no item named 'Column Name'

When I tried using the column df['Column Name'] I got no item named 'Column Name'

我使用df.head()检查了数据框,它显示为一个干净的表,列名与我想要的一样....但是,当我使用re表达式删除(填充)它时无法识别我拥有的列名.

I checked the dataframe using df.head() and it showed up as a clean table with the column names as what I wanted them to be....however when I use the re expression to remove the (stuff) it isn't recognizing the column name that I have.

我通常使用

df['name'].str.replace(" ()","") 

但是,我想删除括号以及其中的内容....如何使用正则表达式或熊猫来做到这一点?

However, I want to remove the parentheses and what is inside....How can I do this using either regex or pandas?

谢谢!

这是我使用的解决方案...感谢您的帮助!

Here is the solution I used...thanks for the help!

All['Manufacturer Standard Name'] = All['Manufacturer Standard Name'].str.replace(r"\(.*\)","")

推荐答案

df['name'].str.replace(r"\(.*\)","")

您不能直接在熊猫对象上运行 re 函数.您必须为对象内的每个元素循环它们.所以Series.str.replace((r"\(.*\)", "")只是Series.apply(lambda x: re.sub(r"\(.*\)", "", x))的语法糖.

You can't run re functions directly on pandas objects. You have to loop them for each element inside the object. So Series.str.replace((r"\(.*\)", "") is just syntactic sugar for Series.apply(lambda x: re.sub(r"\(.*\)", "", x)).

这篇关于如何使用Pandas/Python删除括号和所有数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆