且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除数据框的括号中的内容

更新时间:2022-12-28 14:31:03

a href =http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html =nofollow> 替换

Solution with loop columns and replace:

import pandas as pd

data = pd.DataFrame({'A':['(1)','2','3'],
                   'B':['(B) 77','s gg','d'],
                   'C':['s','(d) 44','f']})

print (data)
     A       B       C
0  (1)  (B) 77       s
1    2    s gg  (d) 44
2    3       d       f

for col in data:
    data[col] = data[col].str.replace(r'\(.*\)', '')
print (data)
   A     B    C
0       77    s
1  2  s gg   44
2  3     d    f

列表理解的解决方案和 concat

Solution with list comprehension and concat:

data = pd.concat([data[col].str.replace(r'\(.*\)', '') for col in data], axis=1)
print (data)
   A     B    C
0       77    s
1  2  s gg   44
2  3     d    f