4

I am trying to replace certain data in the data frame to include the additional 'F'.

The code should look like this:

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

I tried to do this:

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

But it is not changing the values, what is the best way to add the 'F' to the strings if it is NK225M or TOPIXM.

Puneet Sinha
  • 971
  • 1
  • 9
  • 22
lakshmen
  • 27,102
  • 64
  • 169
  • 262

4 Answers4

5

Use isin for test values of list and if match condition add 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

Another solutions with Series.mask or numpy.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'])
jezrael
  • 729,927
  • 78
  • 1,141
  • 1,090
3

Use numpy.where

Ex:

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)

Output:

    pfType
0  NK225MF
1  TOPIXMF
2    Hello
3    World
Rakesh
  • 78,594
  • 17
  • 67
  • 103
1

Use np.where

testdata['pfType'] = np.where(testdata['pfType']=='NK225M', 'NK225MF', testdata['pfType'])
testdata['pfType'] = np.where(testdata['pfType']=='TOPIXM', 'TOPIXMF', testdata['pfType'])
Sociopath
  • 12,395
  • 17
  • 43
  • 69
0

To modify dataframe use below code.

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

(ref.)

shingote
  • 1
  • 2