Ash Upadhyay
Ash Upadhyay

Reputation: 1966

Use two columns of a Pandas DataFrame and add a new column. Python Pandas

I have a dataframe which looks like this

Currency    Amount    Country
EUR         12.06     France
USD         10.23     USA
INR         122.17    India
INR         422.01    India
USD         8.06      USA

I have a function which would take currency name i.e. Currency column and use Amount to convert to a common currency

def convert_an_amount(amount,curr,target_currency):
    if curr in c.currencies:
        return c.convert(amount, curr , target_currency)
    return np.nan

What I want to do is create the column of our dataframe

def convert_to_common(amount,curr_name,target_curr):
    currency_coverted_variable - 
    ... required code ...

I would like to have the following dataframe

Currency    Amount    Country   Common Currency(EUR)
EUR         12.06     France    x
USD         10.23     USA       x
INR         122.17    India     x
INR         422.01    India     x
USD         8.06      USA       x

Is there any way to code this function? I am using a library which would convert the value in the function but how to facilitate the creation of the dataframe?

The condition for c.convert is that it only converts one value at a time!

Upvotes: 1

Views: 280

Answers (2)

marco carminati
marco carminati

Reputation: 54

Here https://chrisalbon.com/python/data_wrangling/pandas_make_new_columns_using_functions/

you can see an example where you create your function (in your case convert_to_common)

# Create a function that takes two inputs, pre and post
def pre_post_difference(pre, post):
    # returns the difference between post and pre
    return post - pre

and then you can call it adding a variable in your dataframe

# Create a variable that is the output of the function
df['score_change'] = pre_post_difference(df['preTestScore'], df['postTestScore'])

# View the dataframe
df

Upvotes: 0

jezrael
jezrael

Reputation: 863166

You can use DataFrame.apply with your function:

df['new'] = df.apply(lambda x: convert_to_common(x['Amount'], x['Currency'], 'EUR'), axis=1)

I think you can create dictionary for rate, then use Series.map and multiple by Amount if need better performance:

eur = {'EUR':1, 'USD':2, 'INR':3}

df['new'] = df['Currency'].map(eur) * df['Amount']
print (df)
  Currency  Amount Country      new
0      EUR   12.06  France    12.06
1      USD   10.23     USA    20.46
2      INR  122.17   India   366.51
3      INR  422.01   India  1266.03
4      USD    8.06     USA    16.12

Detail:

print (df['Currency'].map(d))
0    1
1    2
2    3
3    3
4    2
Name: Currency, dtype: int64

Upvotes: 1

Related Questions