Pandas将一列中的最后三个字符替换为另一列



我在python pandas数据帧中有两列

.55
id 价格 价格_end
a 22,23 .23
b 230450330.55
c 10,55

IIUC使用Series.str.contains作为布尔掩码,然后使用DataFrame.loc为指定列掩码仅设置经过筛选的行以替换:

mask =  mydf['price'].str[-3:].str.contains(',')
s = mydf.loc[mask, 'price_end']
mydf.loc[mask, 'price_end'] = s.str[:-3] + s.str[-3:].str.replace(",", ".")

如果需要用带掩码的另一列重新填充最后3个值(例如,如果有,,则在此(:

print (mydf)
id           price price_end
0  a           22,23       .73
1  b  230,450,330.55       .85
2  c          100,55       .95
mask =  mydf['price'].str[-3:].str.contains(',')
mydf.loc[mask, 'price'] = mydf.loc[mask, 'price'].str[:-3] + mydf['price_end'].str[-3:]
print (mydf)
id           price price_end
0  a           22.73       .73
1  b  230,450,330.55       .85
2  c          100.95       .95

最新更新