我有一个看起来像这样的数据框
Currency Amount Country
EUR 12.06 France
USD 10.23 USA
INR 122.17 India
INR 422.01 India
USD 8.06 USA
我有一个使用货币名称的功能,即 Currency (货币)列,并使用 Amount (金额)转换为通用货币
def convert_an_amount(amount,curr,target_currency):
if curr in c.currencies:
return c.convert(amount, curr , target_currency)
return np.nan
我要做的是创建数据框的列
def convert_to_common(amount,curr_name,target_curr):
currency_coverted_variable -
... required code ...
我想要以下数据框
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
有什么方法可以编码此功能? 我正在使用一个库,该库可以转换函数中的值,但是如何促进数据框的创建?
c.convert的条件是一次只能转换一个值!
答案 0 :(得分:1)
您可以将DataFrame.apply
与功能配合使用:
df['new'] = df.apply(lambda x: convert_to_common(x['Amount'], x['Currency'], 'EUR'), axis=1)
我认为您可以为rate
创建字典,然后使用Series.map
并乘以Amount
以提高性能:
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
详细信息:
print (df['Currency'].map(d))
0 1
1 2
2 3
3 3
4 2
Name: Currency, dtype: int64
答案 1 :(得分:0)
这里 https://chrisalbon.com/python/data_wrangling/pandas_make_new_columns_using_functions/
您会看到一个示例,其中创建了函数(在您的情况下为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
然后您可以调用它在数据框中添加变量
# Create a variable that is the output of the function
df['score_change'] = pre_post_difference(df['preTestScore'], df['postTestScore'])
# View the dataframe
df