简体   繁体   English

从字符串列 python 中提取 substring

[英]Extract substring from a string column python

I have a dataframe like this:我有一个像这样的 dataframe:

name      link
apple    example1.com/dsa/es?id=2812168&width=1200/web/map&resize.html
banana.  example2.com/es?id=28132908&width=1220/web/map_resize.html
orange.  example3.com/es?id=3209908&width=1120/web&map_resize.html

Each name's ID is buried in the link, which may have different structure.每个名称的 ID 都隐藏在链接中,链接可能具有不同的结构。 However, I know that the pattern is 'id=' + 'what I want' + '&'但是,我知道模式是 'id=' + 'what I want' + '&'

I wonder, is there a way to extract the id from link and put it back to the dataframe to get the following:我想知道,有没有办法从link中提取id并将其放回 dataframe 以获得以下信息:

name      link
apple    2812168
banana.  28132908
orange.  3209908

I try to use this:我尝试使用这个:

df['name'] = df['name'].str.extract(r'id=\s*([^\.]*)\s*\\&', expand=False)

but it returns a column with all nan但它返回一个全是nan的列

Also, there may be more than one & in the link此外,链接中可能有多个 &

We can make use of positive lookbehind and positive lookahead :我们可以利用positive lookbehindpositive lookahead

df['link'] = df['link'].str.extract('(?<=id\=)(.*?)(?=\&)')


      name      link
0    apple   2812168
1  banana.  28132908
2  orange.   3209908

Details :详情

  • (?<=id\=) : positive lookbehind on id= (?<=id\=) : 对id=的正面回顾
  • (.*) : everything (.*) : 一切
  • (?=\&width) : positive lookahead on &width (?=\&width) : &width width 的正向前瞻

I think Ids are always numbers, so this is somewhat cleaner:我认为 Ids 总是数字,所以这有点干净:

df["link"] = df['link'].str.extract(r'id=(\d+)&', expand=False)
print(df)
#     name      link
#0   apple   2812168
#1  banana  28132908
#2  orange   3209908

Let tri split让三split

df['link'].str.split('id=').str[1].str.split('&').str[0]
0     2812168
1    28132908
2     3209908
Name: link, dtype: object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM