Python pandas:删除字符串中定界符后的所有内容

新手上路,请多包涵

我有包含例如的数据框:

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

我需要删除两个 :: 的所有内容(包括),以便我最终得到:

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

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

原文由 f0rd42 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 402
2 个回答

您可以使用 pandas.Series.str.split 就像正常使用 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 文档,或者更好的是, 在 pandas 中使用文本数据

原文由 blacksite 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果它在数据框 (名称: 数据框)的特定列 (名称:列) 中,您也可以使用

dataframe.column.str.replace("(::).*","")

它给你下面的结果

         column        new_column
0  vendor a::ProductA  vendor a
1  vendor b::ProductA  vendor b
2  vendor a::Productb  vendor a

通过使用它,您无需指定任何位置,因为它会删除“ :: ”之后的任何内容

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

原文由 Suraj Gowda 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题