替换pandas.DataFrame中的字符串

时间:2015-09-03 23:34:50

标签: python pandas dataframe

所以我想在我的DataFrame中用"."替换所有"-"

例如,

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

这样的事情

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

我尝试了一些方法,但它似乎不起作用,例如stock_frame['Symbol'].apply(lambda x: x.replace(".","-"))

由于

2 个答案:

答案 0 :(得分:2)

如何使用符号系列的str方法呢?

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
>>> 

答案 1 :(得分:0)

您也可以使用pandas自己的replace function ..

重建您的示例DataFrame:

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

现在运行replace命令。

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

结果正是您所寻找的。

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