Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing values that match certain string in dataframe

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.

like image 444
lakshmen Avatar asked Jan 26 '23 20:01

lakshmen


2 Answers

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'])
like image 191
jezrael Avatar answered Jan 31 '23 07:01

jezrael


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
like image 20
Rakesh Avatar answered Jan 31 '23 08:01

Rakesh