将特定行与特定条件相乘 pandas
Multiplie Specific row with specific condition pandas
我想对 pandas 中的列进行倍增,并用计算出的值替换旧值。
示例:
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
)
如果工具以“EUR”结尾,我想将价格乘以汇率 EURUSD 以转换为美元的价格。
结果将是:
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
)
我尝试了以下代码:
df.loc[df["Instrument"].str[-3:] == "EUR",df["Price"]]=df["Price"]*EURUSD
您可以使用 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
我想对 pandas 中的列进行倍增,并用计算出的值替换旧值。
示例:
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
)
如果工具以“EUR”结尾,我想将价格乘以汇率 EURUSD 以转换为美元的价格。
结果将是:
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
)
我尝试了以下代码:
df.loc[df["Instrument"].str[-3:] == "EUR",df["Price"]]=df["Price"]*EURUSD
您可以使用 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