0

I would like to check if a certain column has a certain value in a row. If so, a new column should be created with a value.

I have solved this problem too. Unfortunately my code is very slow. Does anyone have an idea how I could solve this to make it go faster? There must be a more elegant solution.

temp = []
for index, row in df_event.iterrows():
  if row['event'] == ("view"):
    temp.append(1)
  if row['event'] == ("addtocart"):
    temp.append(2)
  if row['event'] == ("transaction"):
    temp.append(3)

df['event'] = temp
df['event'].head()

This is my dataframe and what I want

enter image description here

Each event should get a code. View =1, addtocart = 2, transaction = 3

How could I replace my code with a map function?

  • 1
    Create dictionary and use `map` – jezrael Sep 18 '20 at 12:38
  • 1
    Thank you for your comment. I also looked at this link and did some research. I do not quite understand how I could apply this to my problem. Could you help me with that, please? –  Sep 18 '20 at 12:42
  • 1
    Use `df['code'] = df['event'].map({"view":1, "addtocart":2, "addtocart":3})` – jezrael Sep 18 '20 at 12:46
  • 1
    Thank you very much! And I wish you all the best and a big thank you for your time and effort. Thank you! –  Sep 18 '20 at 12:48
  • You edited the question after it was closed, but I see your problem is already solved. Please only edit the questions that you wish to be reopened. – RichieV Sep 18 '20 at 17:02

0 Answers0