0

So I want to replace all the "." with "-" in my DataFrame.

For instance,

    Symbol  Company                 Sector
230 TRP     TransCanada Corporation Energy
231 TCL.A   Transcontinental Inc.   Industrials

to something like this

    Symbol  Company                 Sector
230 TRP     TransCanada Corporation Energy
231 TCL-A   Transcontinental Inc.   Industrials

I have tried a few method, but it doesn't seems to work, such as stock_frame['Symbol'].apply(lambda x: x.replace(".","-"))

Thanks

2
  • Your code works for me if I modify it to: stock_frame['Symbol'] = stock_frame['Symbol'].apply(lambda x: x.replace(".","-")) Commented Sep 4, 2015 at 0:01
  • @dagrha - I got this error: 'float' object has no attribute 'replace'. I think it apply the function to the index instead of the value. Commented Sep 4, 2015 at 0:21

2 Answers 2

2

How about using the str method of the Symbol Series instead?

Python 2.7.8 (default, Sep 30 2014, 15:34:38) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd
>>> tickers = [('TRP', 'TransCanada Corporation', 'Energy'), ('TCL.A', 'Transcontinental Inc.', 'Industrials')]
>>> tickers
[('TRP', 'TransCanada Corporation', 'Energy'), ('TCL.A', 'Transcontinental Inc.', 'Industrials')]
>>> tickers_df = pd.DataFrame(tickers, columns=['Symbol', 'Company', 'Sector'])
>>> tickers_df
  Symbol                  Company       Sector
0    TRP  TransCanada Corporation       Energy
1  TCL.A    Transcontinental Inc.  Industrials
>>> tickers_df.Symbol= tickers_df.Symbol.str.replace('.','-')
>>> tickers_df
  Symbol                  Company       Sector
0    TRP  TransCanada Corporation       Energy
1  TCL-A    Transcontinental Inc.  Industrials
>>> 
Sign up to request clarification or add additional context in comments.

1 Comment

you da real mvp. Thanks a lot
0

You could also use pandas' own replace function..

Rebuilding your sample DataFrame:

stock_frame = pd.DataFrame({
    'Symbol': ['TRP', 'TCL.A'], 
    'Company': ['TransCanada Corporation', 'Transcontinental Inc.'], 
    'Sector': ['Energy', 'Industrials']})

Now run the replace command.

stock_frame['Symbol'].replace({"\.": "-"}, regex=True, inplace=True)

The result is exactly what you're looking for.

  Symbol  Company                 Sector
0 TRP     TransCanada Corporation Energy
1 TCL-A   Transcontinental Inc.   Industrials

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.