Python Pandas:删除字符串中定界符后的所有内容 [英] Python pandas: remove everything after a delimiter in a string

查看:73
本文介绍了Python Pandas:删除字符串中定界符后的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据帧包含例如:

"vendor a::ProductA"
"vendor b::ProductA
"vendor a::Productb"

我需要删除(和包括)两个::,以便最终得到:

I need to remove everything (and including) the two :: so that I end up with:

"vendor a"
"vendor b"
"vendor a"

我尝试了str.trim(似乎不存在)和str.split,但没有成功. 最简单的方法是什么?

I tried str.trim (which seems to not exist) and str.split without success. what would be the easiest way to accomplish this?

推荐答案

您可以像通常使用split一样使用pandas.Series.str.split.只需拆分字符串'::',并索引通过split方法创建的列表:

You can use pandas.Series.str.split just like you would use split normally. Just split on the string '::', and index the list that's created from the split method:

>>> df = pd.DataFrame({'text': ["vendor a::ProductA", "vendor b::ProductA", "vendor a::Productb"]})
>>> df
                 text
0  vendor a::ProductA
1  vendor b::ProductA
2  vendor a::Productb
>>> df['text_new'] = df['text'].str.split('::').str[0]
>>> df
                 text  text_new
0  vendor a::ProductA  vendor a
1  vendor b::ProductA  vendor b
2  vendor a::Productb  vendor a

这是一个非熊猫解决方案:

Here's a non-pandas solution:

>>> df['text_new1'] = [x.split('::')[0] for x in df['text']]
>>> df
                 text  text_new text_new1
0  vendor a::ProductA  vendor a  vendor a
1  vendor b::ProductA  vendor b  vendor b
2  vendor a::Productb  vendor a  vendor a

这是上面pandas中发生的情况的分步说明:

Here's the step-by-step explanation of what's happening in pandas above:

# Select the pandas.Series object you want
>>> df['text']
0    vendor a::ProductA
1    vendor b::ProductA
2    vendor a::Productb
Name: text, dtype: object

# using pandas.Series.str allows us to implement "normal" string methods 
# (like split) on a Series
>>> df['text'].str
<pandas.core.strings.StringMethods object at 0x110af4e48>

# Now we can use the split method to split on our '::' string. You'll see that
# a Series of lists is returned (just like what you'd see outside of pandas)
>>> df['text'].str.split('::')
0    [vendor a, ProductA]
1    [vendor b, ProductA]
2    [vendor a, Productb]
Name: text, dtype: object

# using the pandas.Series.str method, again, we will be able to index through
# the lists returned in the previous step
>>> df['text'].str.split('::').str
<pandas.core.strings.StringMethods object at 0x110b254a8>

# now we can grab the first item in each list above for our desired output
>>> df['text'].str.split('::').str[0]
0    vendor a
1    vendor b
2    vendor a
Name: text, dtype: object

我建议您查看 pandas.Series. str docs ,或者更好的是,在熊猫中使用文本数据.

I would suggest checking out the pandas.Series.str docs, or, better yet, Working with Text Data in pandas.

这篇关于Python Pandas:删除字符串中定界符后的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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