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
  concat 3 columns of dataframe to one column flash77 2 851 Oct-03-2023, 09:29 PM
Last Post: flash77
  HTML Decoder pandas dataframe column mbrown009 3 1,054 Sep-29-2023, 05:56 PM
Last Post: deanhystad
  attempt to split values from within a dataframe column mbrown009 8 2,375 Apr-10-2023, 02:06 AM
Last Post: mbrown009
  Make unique id in vectorized way based on text data column with similarity scoring ill8 0 894 Dec-12-2022, 03:22 AM
Last Post: ill8
  Pandas Dataframe Filtering based on rows mvdlm 0 1,446 Apr-02-2022, 06:39 PM
Last Post: mvdlm
  Putting column name to dataframe, can't work. jonah88888 1 1,837 Sep-28-2021, 07:45 PM
Last Post: deanhystad
  update values in one dataframe based on another dataframe - Pandas iliasb 2 9,311 Aug-14-2021, 12:38 PM
Last Post: jefsummers
  Pandas Data frame column condition check based on length of the value aditi06 1 2,698 Jul-28-2021, 11:08 AM
Last Post: jefsummers
  Setting the x-axis to a specific column in a dataframe devansing 0 2,040 May-23-2021, 12:11 AM
Last Post: devansing
Question [Solved] How to refer to dataframe column name based on a list lorensa74 1 2,269 May-17-2021, 07:02 AM
Last Post: lorensa74

Forum Jump:

User Panel Messages

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