【问题标题】:Replace commas and dashes in a pandas data frame with blank用空白替换熊猫数据框中的逗号和破折号
【发布时间】:2021-03-03 16:17:32
【问题描述】:

当我在 df 中使用 replace 函数时,它会将所有值变为空白。

df:

SR_NO  NTN          NAME    
1      0000020-4    wang's hong & liang 
2      0000092-2    the bank of khyber ltd  
3      0000094-9    al khair gadoon limited 
4      0000098-1    ace weavers pvt. ltd,
5      0000131-7    niaz private limited    

代码:

dictionary = {'-':'', 'pvt':'private', 'ltd':'limited', '.': '', '&': ' and ', ''':''} 

df.replace(dictionary, regex=True, inplace=True)

我得到的结果是:

SR_NO  NTN          NAME    
1       
2
3
4
5

期望的结果是:

SR_NO  NTN          NAME    
1      00000204     wangs hong and liang    
2      00000922     the bank of khyber limited
3      00000949     al khair gadoon limited 
4      00000981     ace weavers private limited
5      00001317     niaz private limited

【问题讨论】:

    标签: python pandas dataframe replace


    【解决方案1】:

    由于您的用户 regex=True 正则表达式 . 是一切,因此它会导致一个空字符串。要仅替换点,请使用 -

    dictionary = {'-':'', 'pvt':'private', 'ltd':'limited', '\.': '', '&': ' and ', '\'':''}
    

    【讨论】:

      【解决方案2】:

      您需要转义 .,因为选择所有字符串值的特殊正则表达式字符:

      dictionary = {'-':'', 'pvt':'private', 'ltd':'limited', '\.': '', '&': ' and ', "'":''} 
      
      df.replace(dictionary, regex=True, inplace=True)
      
      print (df)
         SR_NO       NTN                          NAME
      0      1  00000204        wangs hong  and  liang
      1      2  00000922    the bank of khyber limited
      2      3  00000949       al khair gadoon limited
      3      4  00000981  ace weavers private limited,
      4      5  00001317          niaz private limited
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多