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.
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'])
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With