首页 > 解决方案 > Pandas 将列中的数字提取到新列中

问题描述

我目前有这个 df,其中 rect 列是所有字符串。我需要从中提取 x、y、w 和 h 到单独的列中。数据集非常大,所以我需要一种有效的方法

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>

到目前为止,此解决方案有效,但是您可以看到它非常混乱

df[['x', 'y', 'w', 'h']] = df['rect'].str.replace('<Rect \(', '').str.replace('\),', ',').str.replace(' by ', ',').str.replace('>', '').str.split(',', n=3, expand=True)

有没有更好的办法?可能是正则表达式方法

标签: pythonpandas

解决方案


使用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

推荐阅读