【问题标题】:Replacing values that match certain string in dataframe替换与数据框中特定字符串匹配的值
【发布时间】:2019-06-21 03:27:04
【问题描述】:

我正在尝试替换数据框中的某些数据以包含额外的“F”。

代码应如下所示:

if testdata['pfType'] =='NK225M'|testdata['pfType'] == 'TOPIXM':
    testdata['pfType'] = ' testdata['pfType'] & 'F';

我尝试过这样做:

testdata['pfType'][testdata['pfType'] == 'NK225M'] = 'NK225MF'
testdata['pfType'][testdata['pfType'] == 'TOPIXM'] = 'TOPIXMF'

但它并没有改变值,如果是 NK225M 或 TOPIXM,将“F”添加到字符串的最佳方法是什么。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    使用isin作为列表的测试值,如果匹配条件添加F

    testdata = pd.DataFrame({'pfType':['NK225M','TOPIXM','AAA']})
    
    vals = ['NK225M','TOPIXM']
    testdata.loc[testdata['pfType'].isin(vals), 'pfType'] += 'F'
    print (testdata)
        pfType
    0  NK225MF
    1  TOPIXMF
    2      AAA
    

    Series.masknumpy.where 的另一种解决方案:

    testdata['pfType'] = testdata['pfType'].mask(testdata['pfType'].isin(vals),
                                                 testdata['pfType'] + 'F')
    

    testdata['pfType'] = np.where(testdata['pfType'].isin(vals), 
                                  testdata['pfType'] + 'F', 
                                  testdata['pfType'])
    

    【讨论】:

      【解决方案2】:

      使用numpy.where

      例如:

      import pandas as pd
      import numpy as np
      
      testdata = pd.DataFrame({"pfType": ['NK225M', 'TOPIXM', "Hello", "World"]})
      testdata['pfType'] = np.where((testdata['pfType'] == "TOPIXM") | (testdata['pfType'] == 'NK225M'), testdata['pfType']+"F", testdata['pfType'])
      print(testdata)
      

      输出:

          pfType
      0  NK225MF
      1  TOPIXMF
      2    Hello
      3    World
      

      【讨论】:

        【解决方案3】:

        使用np.where

        testdata['pfType'] = np.where(testdata['pfType']=='NK225M', 'NK225MF', testdata['pfType'])
        testdata['pfType'] = np.where(testdata['pfType']=='TOPIXM', 'TOPIXMF', testdata['pfType'])
        

        【讨论】:

          【解决方案4】:

          要修改数据框,请使用以下代码。

            testdata.at['pfType', testdata['pfType'] == 'NK225M'] = 'NK225MF'
          

          (ref.)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-12-19
            • 1970-01-01
            • 2015-02-07
            • 2019-12-10
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多