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

2024-05-20 23:08:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有数据帧,其中包含例如:

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

我需要删除所有(包括)这两个::这样我就可以得到:

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

我试过str.trim(看起来不存在)和str.split,但没有成功。 最简单的方法是什么?


Tags: 数据方法splitvendorstrtrimproductaproductb
3条回答

您可以像正常使用split一样使用pandas.Series.str.split。只需对字符串'::'进行拆分,并为从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

以下是非熊猫解决方案:

>>> 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中发生的事情的逐步解释:

# 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,或者更好的是,Working with Text Data in pandas

您可以使用str.replace(":", " ")删除"::"。 若要拆分,需要指定要拆分为的字符:str.split(" ")

trim函数在python中称为strip:str.strip()

另外,您可以通过str[:7]来获得字符串中的"vendor x"

祝你好运

这是你的功能:

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)

把原来的线传进去。把新剪好的绳子拿来。

相关问题 更多 >