How to make a column based on previous values in dataframe

Viewed 69

I have a data frame:

user_id      url
111          google.com
111          youtube.com
111          youtube.com
111          google.com
111          stackoverflow.com
111          google.com
222          twitter.com
222          google.com
222          twitter.com

I want to create a column that will show the fact of visiting this URL before.

Desired output:

user_id      url                 target
111          google.com          0
111          youtube.com         0
111          youtube.com         1
111          google.com          1
111          stackoverflow.com   0
111          google.com          1
222          twitter.com         0
222          google.com          0
222          twitter.com         1

I can do this with a loop but it doesn't look good. Is it possible to make it with pandas?

2 Answers

Use duplicated:

df['target'] = df.duplicated().astype(int)
print(df)

Output

   user_id                url  target
0      111         google.com       0
1      111        youtube.com       0
2      111        youtube.com       1
3      111         google.com       1
4      111  stackoverflow.com       0
5      111         google.com       1
6      222        twitter.com       0
7      222         google.com       0
8      222        twitter.com       1
df['target'] =df.groupby(['user_id','url']).cumcount().gt(0).astype(int)

    user_id            url      target
0      111         google.com       0
1      111        youtube.com       0
2      111        youtube.com       1
3      111         google.com       1
4      111  stackoverflow.com       0
5      111         google.com       1
6      222        twitter.com       0
7      222         google.com       0
8      222        twitter.com       1
Related