Python pandas:删除字符串中分隔符后的所有内容

f0r*_*d42 14 python python-3.x pandas

我有数据框,包含例如:

"vendor a::ProductA"
"vendor b::ProductA
"vendor a::Productb"
Run Code Online (Sandbox Code Playgroud)

我需要删除所有(包括)两个::所以我最终得到:

"vendor a"
"vendor b"
"vendor a"
Run Code Online (Sandbox Code Playgroud)

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

bla*_*ite 40

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

>>> 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
Run Code Online (Sandbox Code Playgroud)

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

>>> 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
Run Code Online (Sandbox Code Playgroud)

编辑:以下是对pandas上述情况的逐步说明:

# 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
Run Code Online (Sandbox Code Playgroud)

我建议查看pandas.Series.str文档,或者更好的是,在pandas中使用Text Data.


小智 10

如果它位于数据框(具有名称:dataframe)的特定列(具有名称:column)中,您还可以使用

dataframe.column.str.replace("(::).*","")
Run Code Online (Sandbox Code Playgroud)

它给你以下结果

         column        new_column       
0  vendor a::ProductA  vendor a
1  vendor b::ProductA  vendor b
2  vendor a::Productb  vendor a
Run Code Online (Sandbox Code Playgroud)

通过使用它,您不需要指定任何位置,因为它会消除“ :: ”之后存在的任何内容

我想这可能会来哦,帮助,祝你好运!