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
  • 803
  • 1
  • 7
  • 20
lakesh
  • 25,623
  • 57
  • 163
  • 254

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
  • 629,482
  • 62
  • 918
  • 895
2

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
  • 75,210
  • 17
  • 57
  • 95
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
  • 11,667
  • 16
  • 38
  • 61
0

To modify dataframe use below code.

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

(ref.)

shingote
  • 1
  • 2