Python pandas: remove everything after a separator in a string

I have data frames that contain, for example:

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

I need to remove all (including) two :: so I get:

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

I tried str.trim (which doesn't seem to exist) and str.split without success. What would be the easiest way to do this?

+4
source share
3 answers

You can use pandas.Series.str.splitas usual split. Just split the line '::'and index the list created using the method 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

Here's the solution is not pandas:

>>> 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

Edit: Here's a step-by-step explanation of what happens in the pandasabove:

# 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 , , pandas.

+7

str.replace( ":", "), "::". , , : str.split("") python: str.strip()

, str [: 7], " x" .

.

+1

there is your function:

def do_it(str):
  integer=0
  while integer<len(str):
      if str[integer]==':' :
        if str[integer+1]==':' :
          str=str.split(':')[0]
          break;
      integer=integer+1    
  return (str)

pass the original string. And get a new cropped string.

-2
source

Source: https://habr.com/ru/post/1661351/


All Articles