Extract substring from string in dataframe

I have the following ddataframe:

                             Company Name        Time Expectation
0                Asta Funding Inc. (ASFI)  9:35 AM ET           -
1                       BlackBerry (BBRY)  7:00 AM ET     ($0.03)
2                    Carnival Corp. (CCL)  9:15 AM ET       $0.09
3                      Carnival PLC (CUK)  0:00 AM ET           -

I would like to have company symbols in my separate column instead of the "Company Name" column. Now I just iterate over the company names, and RE pulls out the characters, puts them in the list, and then I apply it to the new column, but I wonder if there is a cleaner / simpler way.

I'm new to the whole map, reducing lambda stuff.

for company in df['Company Name']:
    ticker = re.search("\(.*\)",company).group(0)
    ticker = ticker[1:len(ticker)-1]
    tickers.append(ticker)
+4
source share
2 answers

Regular expression search is built into the pandas Series class. You can find the documentation here. In your case, you can use

df['ticker'] = df['Company Name'].str.extract("\((.*)\)") 
+11
source

, str . , :

df['Company Symbol'] = df['Company Name'].str.rstrip(')').str.split('(').str[1] # Make new column
df['Company Name'] = df['Company Name'].str.replace(r'\(.*?\)$', '') # Remove symbol from company name
0

All Articles