熊猫从列中提取数字到新列中

时间:2018-09-04 17:59:27

标签: python pandas

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

DataLossError

到目前为止,此解决方案有效,但是您看到的却很混乱

tf.image.resize_image_with_crop_or_pad

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

5 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:5)

内联

制作副本

df.assign(**dict(zip('xywh', df.rect.str.findall('\d+').str)))

                          rect    x    y    w    h
0  <Rect (120,168),260 by 120>  120  168  260  120
1  <Rect (120,168),260 by 120>  120  168  260  120
2  <Rect (120,168),260 by 120>  120  168  260  120
3  <Rect (120,168),260 by 120>  120  168  260  120
4  <Rect (120,168),260 by 120>  120  168  260  120

或者只是重新分配给df

df = df.assign(**dict(zip('xywh', df.rect.str.findall('\d+').str)))

df

                          rect    x    y    w    h
0  <Rect (120,168),260 by 120>  120  168  260  120
1  <Rect (120,168),260 by 120>  120  168  260  120
2  <Rect (120,168),260 by 120>  120  168  260  120
3  <Rect (120,168),260 by 120>  120  168  260  120
4  <Rect (120,168),260 by 120>  120  168  260  120

就地

修改现有的df

df[[*'xywh']] = pd.DataFrame(df.rect.str.findall('\d+').tolist())

df

                          rect    x    y    w    h
0  <Rect (120,168),260 by 120>  120  168  260  120
1  <Rect (120,168),260 by 120>  120  168  260  120
2  <Rect (120,168),260 by 120>  120  168  260  120
3  <Rect (120,168),260 by 120>  120  168  260  120
4  <Rect (120,168),260 by 120>  120  168  260  120

答案 2 :(得分:3)

如果字符串遵循特定格式<Rect \((\d+),(\d+)\),(\d+) by (\d+)>,则可以将此正则表达式与str.extract方法一起使用:

df[['x','y','w','h']] = df.rect.str.extract(r'<Rect \((\d+),(\d+)\),(\d+) by (\d+)>')

df
#                          rect    x    y    w    h
#0  <Rect (120,168),260 by 120>  120  168  260  120
#1  <Rect (120,168),260 by 120>  120  168  260  120
#2  <Rect (120,168),260 by 120>  120  168  260  120
#3  <Rect (120,168),260 by 120>  120  168  260  120
#4  <Rect (120,168),260 by 120>  120  168  260  120

答案 3 :(得分:2)

使用str.extract,它将正则表达式中的组提取到列中:

df['rect'].str.extract(r'\((?P<x>\d+),(?P<y>\d+)\),(?P<w>\d+) by (?P<h>\d+)', expand=True)

结果:

     x    y    w    h
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

答案 4 :(得分:0)

在其中一种情况下,有必要“优化”数据本身,而不是尝试将其变形为消费者想要的内容。将干净的数据更改为专用格式要比将专用格式更改为可移植格式要容易得多。

也就是说,如果您真的要解析这个问题,则可以执行类似的操作

>>> import re
>>> re.findall(r'\d+', '<Rect (120,168),260 by 120>')
['120', '168', '260', '120']
>>>
相关问题