Regex in dataframe (Pandas)

Viewed 79

I have a dataframe with a column like that

COL1
PACK[30% /2 prod.(if fidelity)]
PACK[3.85 € /2 prod.(if fidelity)]
PACK[40% /2nd prod.]
PACK[3.5 € /2 prod.]

I want create other column as following according COL1

fidelity_perc fidelity_euro rem_perc  rem_eu
30           3,85           40        3,5

using regex.

For PACK[40% /2nd prod.] I did (?<=PACK\[)\d+(?=%) but it's also walk for PACK[30% /2 prod.(if fidelity)] and I don't want this.

1 Answers

To get the PACK[40% /2nd prod.], you can use

df['COL1'].str.extract(r'PACK\[(\d[\d.]*)%[^][()]*]', expand=False)

See this regex demo.

To get the PACK[30% /2 prod.(if fidelity)], you can use

df['COL1'].str.extract(r'PACK\[(\d[\d.]*)%[^][]*fidelity[^][]*]', expand=False)

See this regex demo

Similarly, if you need to only find a value if there is a + sign, just replace fidelity with \+:

df['COL1'].str.extract(r'PACK\[(\d[\d.]*)%[^][]*\+[^][]*]', expand=False)

Details

  • PACK\[ - a literal PACK[ string
  • (\d[\d.]*) - Capturing group 1: a digit an then any zero or more digits or dots as many as possible
  • % - a % sign
  • [^][]* - any zero or more chars other than [ and ] as many as possible
  • \+ - a plus
  • fidelity - a fidelity substring
  • [^][]* - any zero or more chars other than [ and ] as many as possible
  • [^][()]* - any zero or more chars other than [, ], ( and ) as many as possible
  • ] - a ] char.
Related