amc amc - 5 months ago 51
Python Question

Pandas make new column from substring slice based on the number in a substring of another column

I have a dataframe called 'table' like this:

import pandas as pd
import numpy as np
table = pd.read_csv(main_data, sep='\t')


And it produces this:

NAME SYMBOL STRING
A blah A34SA
B foo BS2812D
...


How can I create a new column in pandas so I have the following:

NAME SYMBOL STRING NUMBER
A blah A34SA 34
B foo BS2812D 2812


So far I have this:
table['NUMBER'] = table.STRING.str[int(filter(str.isdigit, table.STRING))]
but this function does not work in this context.

Thank you!

Answer

The following should work

table['NUMBER'] = table.STRING.apply(lambda x: int(''.join(filter(str.isdigit, x))))