Home > Back-end >  Python: How to convert value in DF based on rule?
Python: How to convert value in DF based on rule?

Time:06-22

I have a Dataframe with a column full of strings like EURUSD, GBPUSD, CNYUSD and so on:

CCY
GBPUSD
EURUSD
CNYUSD

How can I convert all value in this Column from EURUSD to USDEUR, GBPUSD to USDGBP, etc., like this?

CCY
USDGBP
USDEUR
USDCNY

CodePudding user response:

I don't fully understand what you mean. But if you want to create a new column with the same values you just do.

df['USDEUR']= df['EURUSD'].values

and if you want to rename the column you do

df.rename(columns = {'EURUSD':'USDEUR'}, inplace = True)

CodePudding user response:

df['CCY'] = df['CCY'].apply(lambda x: x[3:]   x[:3])

CodePudding user response:

import pandas as pd

def convertCurrency(value):
    switch = {
        'EURUSD':'USDEUR',
        'GBPUSD': 'USDGBP',
        'CNYUSD': 'USDCNY'
    }
    return switch.get(value, 'invalid')

df = pd.DataFrame({'Currency':['EURUSD', 'GBPUSD', 'CNYUSD']})

df['Currency Converted'] = df['Currency'].apply(convertCurrency)
display(df)

Output:

    Currency    Currency Converted
0   EURUSD      USDEUR
1   GBPUSD      USDGBP
2   CNYUSD      USDCNY

CodePudding user response:

Use vectorial functions:

df['currency'] = df['currency'].str[3:] df['currency'].str[:3]

Or, if you want a conditional replacement (move USD first only if it is second), use a regex:

df['currency'] = df['currency'].str.replace(r'(...)USD', r'USD\1', regex=True)

output:

  currency
0   USDEUR
1   USDGBP
2   USDCNY
  • Related