Home > Software design >  Faster FOR with several IFs to replace values in a dataframe
Faster FOR with several IFs to replace values in a dataframe

Time:12-10

I got this code that replaces some values for others but it takes some time to compute in large dbs. Is there a way to do it in a faster way? More pandas-esque?

for i in range(balances.shape[0]):
    if balances["coin"].iloc[i] == "balance.fiat.USD":
        balances["coin"].iloc[i] = "USD"
    elif balances["coin"].iloc[i] == "balance.fiat.ARS":
        balances["coin"].iloc[i] = "ARS"
    elif balances["coin"].iloc[i] == "balance.crypto.AUST.amount":
        balances["coin"].iloc[i] = "AUST"
    else:
        balances["coin"].iloc[i] = "CRYPTO"

CodePudding user response:

This should work:

mapping = {
    "balance.fiat.USD": "USD",
    "balance.fiat.ARS": "ARS",
    "balance.crypto.AUST.amount": "AUST",
}
balances["coin"] = balances["coin"].map(mapping).fillna("CRYPTO")
  • Related