Python Forum
Newbie question to use lambda on multiple columns of a dataframe
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Newbie question to use lambda on multiple columns of a dataframe
#1
data={'id': [0,1,2,3], 'A':[1.1, 1.2, 1.3, 1.4], 'B':[1.0, 1.1, 1.2, 1.3], 'C':[1.1, 1.1, 1.3, 1.3], 'D':[10.0, 20.0, 30.0, 40.0]}
df0=pd.DataFrame(data)
df1=df0.set_index('id')

def get_sum(df):
    sum1= df.apply(lambda x: x['C'] * x['D'] if x['C'] >= x['A'] else (-1.0 * x['C'] * x['D']))
    return(sum1)
Hello:
I want to write a function to return a conditional results.
The condition is:
from my dataframe df1, if the value of column 'C' is equal or greater than column 'A', then return the multiplication of column 'C' and column 'D'; if if the value of column 'C' is equal or smaller than column 'B', then return the negative multiplication of column 'C' and column 'D'; if the value of column 'C' is between column 'A' and column 'B', then return 0.0
In the above example,
I want to return the following results:
[11.0, -22.0, 39.0, -52.0]
However, I don't know how to write the 3 conditions in lambda expression; besides, my above code didn't work.
If you have other idea can do this without lambda is also OK, please advice.
Thanks,
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How is pandas modifying all rows in an assignment - python-newbie question markm74 1 652 Nov-28-2023, 10:36 PM
Last Post: deanhystad
  newbie question - can't make code work tronic72 2 626 Oct-22-2023, 09:08 PM
Last Post: tronic72
  Newbie question about switching between files - Python/Pycharm Busby222 3 543 Oct-15-2023, 03:16 PM
Last Post: deanhystad
  Question on pandas.dataframe merging two colums shomikc 4 782 Jun-29-2023, 11:30 AM
Last Post: snippsat
  [Newbie] Multiple Array azhuda 3 952 Jun-01-2023, 04:29 AM
Last Post: azhuda
  Newbie.... run for cover. OpenCV question Stevolution2023 2 921 Apr-12-2023, 12:57 PM
Last Post: Stevolution2023
  How to check multiple columns value within range SamLiu 2 1,100 Mar-13-2023, 09:32 AM
Last Post: SamLiu
  numpy newbie question bcwilly_ca 4 1,127 Feb-10-2023, 05:55 PM
Last Post: jefsummers
  Converting a json file to a dataframe with rows and columns eyavuz21 13 4,162 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  Nested for loops: Iterating over columns of a DataFrame to plot on subplots dm222 0 1,638 Aug-19-2022, 11:07 AM
Last Post: dm222

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020