mmbbb
mmbbb

Reputation: 39

Create a new category by using a value from another column

My dataset currently has 1 column with different opportunity types. I have another column with a dummy variable as to whether or not the opportunity is a first time client or not.

import pandas as pd

df = pd.DataFrame(
  {"col_opptype": ["a", "b", "c", "d"],
  "col_first": [1,0,1,0] }
  )

I would like to create a new category within col_opptype based on col_first. Where only 1 category (i.e. a) will be matched to its corresponding col_first I.e.,

where:

desired output:

  col_opptype  col_first
0     a_first          1
1           b          0
2           c          1
3  a_notfirst          0

I am working on Python and am a relatively new user so I hope the above makes sense. Thank you!

Upvotes: 1

Views: 421

Answers (1)

Semmel
Semmel

Reputation: 575

This should solve your problem :) Please add your code attempty and at least an example dataframe definition to your next question, so we do not have to invent examples to help you. An exact example of what the final result should look like would also have been great :)

Edit I adjusted the code to your changed question.

import pandas as pd

df = pd.DataFrame(
  {"col_opptype": ["a", "b", "c", "d"],
  "col_first": [1,0,1,0] }
  )
def is_first_opptype(opptype: str, wanted_type:str, first: int):
  if first and opptype == wanted_type:
    return opptype + "_first"
  elif not first and opptype == wanted_type:
    return opptype + "_notfirst"
  else:
    return opptype
df["col_opptype"] = df.apply(lambda x: is_first_opptype(x["col_opptype"], 
x["col_first"], "a"), axis=1)

print(df)

output:

  col_opptype  col_first
0     a_first          1
1           b          0
2           c          1
3           d          0

Upvotes: 1

Related Questions