lak*_*esh 4 python dataframe pandas
我正在尝试替换数据框中的某些数据以包含额外的“F”。
代码应如下所示:
if testdata['pfType'] =='NK225M'|testdata['pfType'] == 'TOPIXM':
testdata['pfType'] = ' testdata['pfType'] & 'F';
Run Code Online (Sandbox Code Playgroud)
我试图这样做:
testdata['pfType'][testdata['pfType'] == 'NK225M'] = 'NK225MF'
testdata['pfType'][testdata['pfType'] == 'TOPIXM'] = 'TOPIXMF'
Run Code Online (Sandbox Code Playgroud)
但它并没有改变这些值,如果它是 NK225M 或 TOPIXM,那么将“F”添加到字符串的最佳方法是什么。
使用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
Run Code Online (Sandbox Code Playgroud)
使用Series.mask或的另一种解决方案numpy.where:
testdata['pfType'] = testdata['pfType'].mask(testdata['pfType'].isin(vals),
testdata['pfType'] + 'F')
Run Code Online (Sandbox Code Playgroud)
testdata['pfType'] = np.where(testdata['pfType'].isin(vals),
testdata['pfType'] + 'F',
testdata['pfType'])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
323 次 |
| 最近记录: |