根据括号位置对 Pandas 数据框值使用 str.split [英] Using str.split for pandas dataframe values based on parentheses location

查看:42
本文介绍了根据括号位置对 Pandas 数据框值使用 str.split的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下数据框系列 df['Name'] 列:

Let's say I have the following dataframe series df['Name'] column:

         Name
       'Jerry'
  'Adam (and family)'
'Paul and Hellen (and family):\n'
'John and Peter (and family):/n'

如何删除 Name 中第一个括号后的所有内容?

How would I remove all the contents in Name after the first parentheses?

df['Name']= df['Name'].str.split("'(").str[0] 

似乎不起作用,我不明白为什么?

doesn't seem to work and I don't understand why?

我想要的输出是

         Name
       'Jerry'
        'Adam'
    'Paul and Hellen'
    'John and Peter'

所以删除括号后的所有内容.

so everything after the parentheses is deleted.

推荐答案

split - 是必要的转义 ( by \:

df['Name']= df['Name'].str.split("\s+\(").str[0]
print (df)
               Name
0           'Jerry'
1             'Adam
2  'Paul and Hellen
3   'John and Peter

使用 regex替换:

Solution with regex and replace:

df['Name']= df['Name'].str.replace("\s+\(.*$", "")
print (df)
               Name
0           'Jerry'
1             'Adam
2  'Paul and Hellen
3   'John and Peter

\s+\(.*$ 表示从可选的空格替换,第一个(到字符串$的结尾code> 到 "" - 空字符串.

\s+\(.*$ means replace from optional whitespace, first ( to the end of string $ to "" - empty string.

这篇关于根据括号位置对 Pandas 数据框值使用 str.split的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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