Home > Back-end >  How to extract numbers and characters from a string Python pandas?
How to extract numbers and characters from a string Python pandas?

Time:07-07

I have a dataset that mixes numeric and character data. I would like to extract only the numerical data and letter "W" (i don't need '2 x HDMI | 2 x USB'....) .

for exemple in this case (20 W, 30W etc). thank you for your help

v=['2 x HDMI | 2 x USB', '20 W Speaker Output', '10 W Speaker Output',
       '20 W Speaker Output', '20 W Speaker Output',
       '20 W Speaker Output', '20 W Speaker Output', '20 Speaker Output',
       '20 W Speaker Output', '20 W Speaker Output',
       '30 W Speaker Output', '20 W Speaker Output',
       '20 W Speaker Output', '2 x HDMI | 2 x USB', '20 W Speaker Output',
       '20 Speaker Output', '24 W Speaker Output', '20 W Speaker Output']

df=pd.DataFrame({"col_1":v})

CodePudding user response:

You can use regular expressions and a little bit of list comprehension trickery to get what you desire:

import re
import pandas as pd

v=['2 x HDMI | 2 x USB', '20 W Speaker Output', '10 W Speaker Output',
       '20 W Speaker Output', '20 W Speaker Output',
       '20 W Speaker Output', '20 W Speaker Output', '20 Speaker Output',
       '20 W Speaker Output', '20 W Speaker Output',
       '30 W Speaker Output', '20 W Speaker Output',
       '20 W Speaker Output', '2 x HDMI | 2 x USB', '20 W Speaker Output',
       '20 Speaker Output', '24 W Speaker Output', '20 W Speaker Output']

df=pd.DataFrame({"col_1":[v.group(0) for v in [re.search('\d \s?[Ww]', v) for v in v] if v]})

... results in:

>>> df
   col_1
0   20 W
1   10 W
2   20 W
3   20 W
4   20 W
5   20 W
6   20 W
7   20 W
8   30 W
9   20 W
10  20 W
11  20 W
12  24 W
13  20 W

CodePudding user response:

Try:

import re
for x in v:
    ms = re.compile(r'\d \s[wW]')
    m = re.search(ms, x)
    print(m.group())

CodePudding user response:

print(df['col_1'].str.extract(r'(\d  [W])*'))

This above extract method with regex, will filter as expected, then clear Nan value.

  • Related