替换与datafram中特定字符串匹配的值

2024-10-01 11:25:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图替换数据框中的某些数据,以包含附加的“F”。你知道吗

代码应如下所示:

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

我试着这么做:

testdata['pfType'][testdata['pfType'] == 'NK225M'] = 'NK225MF'
testdata['pfType'][testdata['pfType'] == 'TOPIXM'] = 'TOPIXMF'

但它不会改变值,如果是NK225M或TOPIXM,那么向字符串中添加“F”的最佳方法是什么。你知道吗


Tags: 数据方法字符串代码iftestdatatopixmnk225m
3条回答

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

具有^{}^{}的其他解决方案:

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'])

使用np.where

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

使用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

相关问题 更多 >