python - 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)
有没有更好的办法?可能是正则表达式方法
解决方案
使用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
推荐阅读
- python - 试图将用户的输入严格控制为仅正数
- android - Jetpack compose + TextInputLayout endIconDrawable 未正确显示
- python - facebook_business 按表单 ID 检索潜在客户
- c++ - 将 3 个文件合并在一起,在合并相同的三个文件时可以正常工作,但是当合并 3 个不同的文件时,它不想读取第 3 个文件
- c++ - 堆栈与堆 - *vector 内的对象是否应声明为指针?
- python-3.x - 当我尝试在添加了噪声的二进制图像上使用 opencv 的morphologyEx 函数时,它会引发错误
- css - 是否有用于背景附件的 css 替代方案:已修复设置为覆盖的背景图像
- .net - 总是从 IWebHostEnvironment 和 IHttpContextAccessor 获取空值
- java - IntelliJ 不提示变量上的可用函数/对象
- flutter - 任务“:audioplayers:compileDebugKotlin”执行失败