I want to multiple a column in pandas and replace the old value by the value computed.
Example :
EURUSD = 2
print(df)
Instrument Price,
1 BTC/EUR 40000
2 ETH/EUR 3000
3 SOL/USD 3200
4 ADA/EUR 2.2
5 DOT/USD 29
)
If the instrument ends by "EUR", I would like to multiply the price by the exchange rate EURUSD to convert the price in USD.
The result would be :
print(df)
Instrument Price,
1 BTC/EUR 80000
2 ETH/EUR 6000
3 SOL/USD 3200
4 ADA/EUR 4.4
5 DOT/USD 29
)
I tried the following code :
df.loc[df["Instrument"].str[-3:] == "EUR",df["Price"]]=df["Price"]*EURUSD
CodePudding user response:
You can use np.where with Series.str.contains:
In [167]: import numpy as np
# Check whether the 'Instrument' value contains 'EUR', if TRUE then PRICE * 2, otherwise leave PRICE as is.
In [168]: df['Price'] = np.where(df.Instrument.str.contains('EUR'), df.Price.mul(2), df.Price)
In [169]: df
Out[169]:
Instrument Price
1 BTC/EUR 80000.0
2 ETH/EUR 6000.0
3 SOL/USD 3200.0
4 ADA/EUR 4.4
5 DOT/USD 29.0
CodePudding user response:
Pass correct loc format
df.loc[df["Instrument"].str[-3:] == "EUR","Price"] = df["Price"]*EURUSD
df
Out[419]:
Instrument Price
1 BTC/EUR 80000.0
2 ETH/EUR 6000.0
3 SOL/USD 3200.0
4 ADA/EUR 4.4
5 DOT/USD 29.0
