pandas 从列中提取数字到新列中 [英] Pandas extract numbers from column into new columns
本文介绍了 pandas 从列中提取数字到新列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前有这个df,其中rect列是所有字符串.我需要从中提取x,y,w和h到单独的列中.数据集非常大,所以我需要一种有效的方法
I currently have this df where the rect column is all strings. I need to extract the x, y, w and h from it into separate columns. The dataset is very large so I need an efficient approach
df['rect'].head()
0 <Rect (120,168),260 by 120>
1 <Rect (120,168),260 by 120>
2 <Rect (120,168),260 by 120>
3 <Rect (120,168),260 by 120>
4 <Rect (120,168),260 by 120>
到目前为止,此解决方案有效,但是您看到的却很混乱
So far this solution works however it's very messy as you can see
df[['x', 'y', 'w', 'h']] = df['rect'].str.replace('<Rect \(', '').str.replace('\),', ',').str.replace(' by ', ',').str.replace('>', '').str.split(',', n=3, expand=True)
有更好的方法吗?可能是正则表达式方法
Is there a better way? Possibly a regex approach
推荐答案
使用extractall
df[['x', 'y', 'w', 'h']] = df['rect'].str.extractall('(\d+)').unstack().loc[:,0]
Out[267]:
match 0 1 2 3
0 120 168 260 120
1 120 168 260 120
2 120 168 260 120
3 120 168 260 120
4 120 168 260 120
这篇关于 pandas 从列中提取数字到新列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文