替换与数据框中的某些字符串匹配的值

时间:2019-01-28 06:39:17

标签: python pandas dataframe

我正在尝试替换数据框中的某些数据以包括附加的“ F”。

代码应如下所示:

this.mainService.getVamData(this.paramData.Eid,'SectionA')
.subscribe(result=>{
  this.data=result;
console.log(this.data);
})

我试图这样做:

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

但是它并没有改变值,如果是NK225M或TOPIXM,最好的方法是将'F'添加到字符串中。

4 个答案:

答案 0 :(得分:4)

使用isin作为列表的测试值,如果匹配条件添加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

使用Series.masknumpy.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'])

答案 1 :(得分:2)

使用numpy.where

例如:

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)

输出:

    pfType
0  NK225MF
1  TOPIXMF
2    Hello
3    World

答案 2 :(得分:1)

使用np.where

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

答案 3 :(得分:0)

要修改数据框,请使用以下代码。

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

ref。)