Python Forum
New Dataframe Column Based on Several Conditions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
New Dataframe Column Based on Several Conditions
#1
I am trying to add a new column to my dataframe based on several complex conditions. I have attached a sample of what I have, along with the column I am trying to add (highlighted). I have a table with customer IDs and revenues for 2021, 2020, 2019, 2018, and 2017. I want to add a "customer status" column that is based off of the revenue columns, and will be populated with the following selections based on the following conditions:

- 2021 New – Positive revenue in 2021 but no (or negative) billings in 2020, 2019, 2018, and 2017.
- 2021 Lost – No (or negative) revenue in 2021, but positive revenue in 2020.
- 2021 Renewed – Positive revenue in 2021, no (or negative) revenue in 2020, and positive revenue in either or all of 2019, 2018, or 2017.
- N/A – Negative or zero revenue in 2021 and negative or zero revenue in 2020
- 2021 Existing – Positive revenue in 2021 and positive revenue in 2020

I have tried using np.select, for loops, and other methods, but the number of conditions is giving me trouble.

Attached Files

.csv   Book1.csv (Size: 592 bytes / Downloads: 3)
Reply
#2
Sounds like a case for pandas.apply()
Basically, you create a function that will determine the value to be assigned. This allows you to have lots of complicated expressions involved, and then the function returns the value to be placed in the new column.
See https://pandas.pydata.org/docs/reference...apply.html
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Putting column name to dataframe, can't work. jonah88888 1 537 Sep-28-2021, 07:45 PM
Last Post: deanhystad
  update values in one dataframe based on another dataframe - Pandas iliasb 2 2,040 Aug-14-2021, 12:38 PM
Last Post: jefsummers
  Pandas Data frame column condition check based on length of the value aditi06 1 815 Jul-28-2021, 11:08 AM
Last Post: jefsummers
  Setting the x-axis to a specific column in a dataframe devansing 0 834 May-23-2021, 12:11 AM
Last Post: devansing
Question [Solved] How to refer to dataframe column name based on a list lorensa74 1 941 May-17-2021, 07:02 AM
Last Post: lorensa74
  Add column based on others timste 8 1,631 Apr-03-2021, 07:39 AM
Last Post: devesh_sahu
Question Pandas - Creating additional column in dataframe from another column Azureaus 2 1,219 Jan-11-2021, 09:53 PM
Last Post: Azureaus
  Buliding a dataframe with where conditions cspower 2 812 Oct-26-2020, 01:55 PM
Last Post: cspower
  Extracting rows based on condition on one column Robotguy 2 987 Aug-07-2020, 02:27 AM
Last Post: Robotguy
  Filter data based on a value from another dataframe column and create a file using lo pawanmtm 1 2,705 Jul-15-2020, 06:20 PM
Last Post: pawanmtm

Forum Jump:

User Panel Messages

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