简体   繁体   中英

Python: How to apply a function to a column based on values from other columns

I am trying to run a currency conversion function on a table so that if the currency in the each row isn't already in the converted currency it changes it. I am using pandas, and have looked into the docs on numpy but have not been able to solve the issue.

So far I have this:

    price   currency
0   11184.86    EUR
1   17277.48    PLN
2   26273.80    XOF
3   86425.94    BRL
4   7179.07     KGS
... ... ...
995 34489.28    PHP
996 35062.02    CNY
997 73420.41    PHP
998 94584.51    CNY
999 84047.74    KWD

I'm trying to add a column for the converted currency using a function that converts all currencies based on the currency input. For example if I choose EUR then row one would have a None value in the new column but the other non-EUR rows would be converted. The function I'm using need the following:

converter(current_currency, conv_currency, ammount)

So I'm trying to create and extra column that takes the value of currency column and price column and generates the new column like so:

    price   currency   f'currency({conv_currency})'
0   11184.86    EUR
1   17277.48    PLN
2   26273.80    XOF
3   86425.94    BRL
4   7179.07     KGS
... ... ...
995 34489.28    PHP
996 35062.02    CNY
997 73420.41    PHP
998 94584.51    CNY
999 84047.74    KWD

I've been using this to try get it to work but I don't know where to go from here:

df[f'currency({conv_currency})] 
df.loc[df["currency"] != currency, f'currency({conv_currency})'] = df['price'].map()

EDIT:

I've been working on it for a little and this is how far I've gotten but I'm struggling to extract the current currency to plug into the method.

df[f'conv currency ({conv_cur})'] = df.loc[df['currency'] != conv_cur]['price'].map(lambda x: cc.convert(still_need_this_value, conv_cur, x))

Since both columns are needed as input, we can't expect to just map a Series - we'd need to get corresponding values from the other column, and as you've noted, don't have an obvious way to do that.

Instead, let's .apply on the entire DataFrame. Since we want to consider rows, we will use axis=1 . Then, our function will accept a row of the original, and can access the individual cells via the normal subscripting or attribute access.

The function we want to use simply wraps converter to pass the cell values in the appropriate places, along with the hard-coded conv_currency which is the same across the entire new column. Finally we can assign those apply results to make the new column.

Putting it all together gives something like:

df[f'currency({conv_currency})'] = df.apply(
    lambda row: converter(row.currency, conv_currency, row.price),
    axis=1
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM