Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

python - 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.,

  • col_opptype = {a_first, a_notfirst, b, c, d}
  • col_first = {1, 0}

where:

  • a_first is when col_opptype = a and col_first = 1
  • a_notfirst is when col_opptype = a and col_first = 0

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!

question from:https://stackoverflow.com/questions/66060069/create-a-new-category-by-using-a-value-from-another-column

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...