Counting the number of unique words in a dataframe with Python

Viewed 61

I'm Python newbie. I didn't a solution for the following problem :

I got this type of dataframe which represents a sequence of touchpoint :

    df = pd.DataFrame({'path' : ['a>b>c','b>b','c>c','b>d','a>c>c']})

    path
    a>b>c
    b>b
    c>c
    b>d
    a>c>c

I neeed to count the number of unique touchpoint for each row and obtain :

    path    count_unique_touchpoint
    a>b>c   3
    b>b     1
    c>c     1
    b>d     2
    a>c>c   2

Many thanks in advance.

1 Answers

You can use Series.str.split to split the strings around the delimiter > then use Series.apply to apply a custom function which maps each of the item of this series to the number of distinct elements it contains. Use:

df["count_unique_touchpoint"] = df["path"].str.split(">").apply(lambda s: len(set(s)))
print(df)

This prints:

    path  count_unique_touchpoint
0  a>b>c                        3
1    b>b                        1
2    c>c                        1
3    b>d                        2
4  a>c>c                        2
Related