
[英]Replace value in column B using dictionary if column A is equal to specific value
[英]How to replace a value in column A where column B is equal to value?
如果 B 列中的值等于 VendorA,我想用 A 列中的任何内容替换字符串的开头(前 5 个字符)。 在没有上述条件的情况下,我没有进一步替换值。
我尝试了以下代码:
ColumnA Vendor
1 A ABBC/1234
2 B BCCD/1234
3 B 1234
4 C 1234ABBC/
Dataset.ColumnA= Dataset.ColumnA.replace(regex=['ABBC/'], value='')
#This should be the output
ColumnA Vendor
1 A 1234
2 B BCCD/1234
3 B 1234
4 C 1234ABBC/
您可以在“/”上拆分并使用np.where
仅在“A”上指定。
df['Vendor'] = np.where(df['ColumnA'].eq('A'), df['Vendor'].str.split('/').str[1], df['Vendor'])
>>> df = pd.DataFrame({'ColumnA':['A','B', 'B', 'C'], 'Vendor':['ABBC/1234','BCCD/1234','1234','1234ABBC/']})
>>> cola = ''.join(df['ColumnA'].values.tolist())
>>> df['Vendor'] = df.apply(lambda row: row['Vendor'].split('/')[1] if row['Vendor'].startswith(cola) else row['Vendor'], axis=1)
>>> df
ColumnA Vendor
0 A 1234
1 B BCCD/1234
2 B 1234
3 C 1234ABBC/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.