使用正则表达式在python中的数据框或列中的大写字母前添加空格 [英] Add space before capital letters in a dataframe or column in python using regex
本文介绍了使用正则表达式在python中的数据框或列中的大写字母前添加空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将大写字母所在的列中的值分开.所以看起来像这样:
I need to have the values in the columns split up where the capital letters are. So it looks like this:
西阿富汗或东北阿富汗
到目前为止,我没有尝试过任何操作.我宁愿不要遍历每一栏.是否可以在没有for循环的情况下(可能使用apply_all或lambda或两者结合使用)?
I tried this so far and nothing changes. I would prefer to not go through every column. Is this possible to do without the for loop, possibly using apply_all or lambda, or a combination of the two?
afg_regions['U.N. Region'].replace(('[A-z]','[A-z]*(\s)[A-z]*'),regex=True,inplace=True)
推荐答案
Use Series.str.replace
with replace uppercase
by same vales with space before and then remove first space:
df = pd.DataFrame({'U.N.Region':['WestAfghanistan','NorthEastAfghanistan']})
df['U.N.Region'] = df['U.N.Region'].str.replace( r"([A-Z])", r" \1").str.strip()
print (df)
U.N.Region
0 West Afghanistan
1 North East Afghanistan
这篇关于使用正则表达式在python中的数据框或列中的大写字母前添加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文