• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Python: How to apply a function to a column based on values from other columns

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

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

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:
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:
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:
I’ve been using this to try get it to work but I don’t know where to go from here:
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.

Answer:

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:

If you have better answer, please add a comment about this, thank you!

dataframe numpy pandas python
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How to get Union type from an array of objects in Flow?

24/03/2023

Resolved: Modify entity using Action in C#

24/03/2023

Resolved: How to give rank on datetime column group by another column with userid in it

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.