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.

4 Answers 4

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'])
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

Use np.where

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

Comments

0

To modify dataframe use below code.

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

(ref.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.