I want to multiply the UNIT column by 2 if the string 'BUY2' is available in the Item Description Column.
DF:
UNIT | Item_Description
2 | BUY1
4 | BUY1
7 | BUY2
4 | BUY3
12 | BUY3
Code: not Working :(
if DF['Item_Description'].str.contains('BUY2').any():
DF['UNIT'] * 2
else:
DF['UNIT']
CodePudding user response:
df = pd.DataFrame({"unit":[2,4,7,4,12],
"ID":["BUY1", "BUY1", "BUY2", "BUY3", "BUY3"]})
df["unit"] = np.where(df["ID"]=="BUY2", df["unit"]*2, df["unit"])
CodePudding user response:
You meant:
if DF['Item_Description'].str.contains('BUY2').any():
DF['UNIT'] *= 2
You need to assign it back.
It's the same logic as:
if DF['Item_Description'].str.contains('BUY2').any():
DF['UNIT'] = DF['UNIT'] * 2
Or if you want to do it on specific rows:
DF.loc[DF['Item_Description'].str.contains('BUY2'), 'UNIT'] *= 2